How can I find elements by text content with jQuery?

In this tutorial, we'll discuss how to find the DOM element by using the text as the context in jQuery?
Submitted by Pratishtha Saxena, on July 22, 2022

jQuery :contains() Selector

There is a selector in jQuery for finding the elements using the text content as a reference. We can use :contains() selector of jQuery.

This selector selects the HTML-DOM element that contains the specified text/string within the brackets.

Syntax:

tagName:contains(text...);

We can check whether the particular tag or element contains the specified text or string in it. The text/string here is always case sensitive, i.e, "ABC" and "abc" are considered as two different strings here.

Example:

HTML:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   </head>
   <body>
      <h1>This is Heading 1.</h1>
      <p class="one">This is a Paragraph.</p>
      <div>This is first div element.</div>
      <div>This is second div element.</div>
   </body>
</html>

jQuery Function:

<script>
    $(document).ready(function(){
      $("div:contains(element)").css("font-weight","bold").css("color","blue");
    });
</script>

Output:

Example: Find elements by text content


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.