×

jQuery Tutorial

jQuery Examples

jQuery Practice

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





Comments and Discussions!

Load comments ↻





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