jQuery :contains() Selector

jQuery | :contains() Selector: Learn about the :contains() Selector with its usages, syntax, examples.
Submitted by Pratishtha Saxena, on December 15, 2022

:contains() Selector

In jQuery, selectors are a parameter through which we can select the HTML element. Selectors can comprise – class names, ids, tag names, attributes, etc. Basically, by using selectors, the appropriate HTML-DOM element can be selected and hence performed actions on it. Here, we are discussing the jQuery :contains() Selector.

The jQuery :contains() selector allows you to select the element that contains a specific string in it. You can specify the string on the basis of which the elements can be filtered out. The mentioned string is searched all over the document and hence, it provides you with the elements containing that string.

:contains() Selector Syntax

$('element : contains(text)');

This selector needs a required parameter – text, which is the string that you specify over here to be searched. The selector is used along with ':' symbol in front.

The example below shows the selection of the elements which contain the string – 'Hey' within them. The string can also be a part of the word in that element text.

jQuery :contains() Selector Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>jQuery - Contains(Text) Selector</h2>
    <p>Click the button to select the elements with string containg - 'Hey'</p>
    <button>Select 'Hey'</button>
    <hr>
    <h3>Hey, Welcome to Include Help !</h3>
    <p>This is a jQuery Tutotrial.</p>
    <h3>Thanks For Visiting !</h3>
    <hr>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $("h3:contains('Hey')").css('color','#FE8700');
        });
    });
  </script>
</html>

Output:

Example 1: jQuery :contains() Selector


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.