Как найти элемент с текстом jquery

All answers so far do not match all specific elements containing a direct child text node which contains a specific text.

Consider the following example. We want to find all hobbits, that is, all divs containing a direct child text node, which contains the word “hobbit” (including word borders, ignoring the case).

$(function() {
    
    const ELEMTYPE = Node.ELEMENT_NODE
    const TEXTTYPE = Node.TEXT_NODE
    
    /*
    Behaves a bit like Python's os.walk().
    The `topdown` parameter is not strictly necessary for this example.
    */
    function* walk_text(root, topdown=true) {
        const childs = []
        const textchilds = []
        for (const child of root.childNodes) {
            const childtype = child.nodeType
            if (childtype === ELEMTYPE) {
                childs.push(child)
            } else if (childtype === TEXTTYPE) {
                textchilds.push(child)
            }
        }
        if (topdown) {
            yield [root, textchilds]
        }
        for (const child of childs) {
            yield* walk_text(child, topdown)
        }
        if (!topdown) {
            yield [root, textchilds]
        }
    }
    
    function* walk_matching(startnode, nodepat, textpat) {
        for ( [elem, textchilds] of walk_text(startnode) ) {
            if ( nodepat.test(elem.nodeName) ) {
                for ( const textchild of textchilds ) {
                    if ( textpat.test(textchild.nodeValue) ) {
                        yield elem
                        break
                    }
                }
            }
        }
    }
    
    // raw dom node
    let startnode = $('body')[0]
    
    // search for element nodes with names matching this pattern ...
    let nodepat = /^div$/i
    
    // ... containing direct child text nodes matching this pattern
    let textpat = /bhobbitb/i
    
    for ( const node of walk_matching( startnode, nodepat, textpat ) ) {
        $(node).css({
            border: '1px solid black',
            color: 'black'
        })
    }

});
div {
    margin:10px 0;
    padding: 10px;
    border: 1px solid silver;
    color: silver;
    font-style:italic;
}

div:before {
    display:block;
    content: attr(name);
    font-style:normal;
}

/* Inserted by SO, we are not interested in it */
body + div {
    display: none;
}
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Find the hobbits</title>
    </head>
    <body>
        <div name='Tolkien'>
            book writer
            <div name='Elrond'>
                elven king
                <div name='Arwen'>elven princess</div>
                <div name='Aragorn'>human king, son-in-law</div>
            </div>
            <div name='Gandalf'>
                wizard, expert for hobbits
                <div name='Bilbo'>
                    old hobbit
                    <div name='Frodo'>
                        young hobbit
                        <div name='Samweis'>best friend hobbit</div>
                    </div>
                </div>
                <div name='Gollum'>ex hobbit</div>
                <div name='Odo'>hobbit</div>
            </div>
        </div>
        <script src= "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </body>
</html>

The other answers find (when searching for ‘hobbit’):

  • Rocket Hazmat’s answer: Tolkien, Gandalf, Bilbo, Frodo, Samweis, Gollum, Odo
  • Morgs’s answer: Tolkien
  • yoav barnea’s answer: Gandalf, Frodo
  • Nicholas Sushkin’s answer: Samweis, Gollum, Odo
  • Rocket Hazmat’s answer in the comments, Terry Lin’s answer, rplaurindo’s answer: Odo

All of these answers make sense, depending on what you want to do. Choose wise, because Rocket Hazmat’s answers, Morgs’s answer and Terry Lin’s answer partially perform more than two times faster than my solution. I guess that is because they don’t need to walk through the whole DOM. Most answers who use .filter() perform very fast.

contains selector

Description: Select all elements that contain the specified text.

  • version added: 1.1.4jQuery( “:contains(text)” )

    text: A string of text to look for. It’s case sensitive.

The matching text can appear directly within the selected element, in any of that element’s descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of :contains() can be written as a bare word or surrounded by quotation marks. The text must have matching case to be selected.

Example:

Finds all divs containing “John” and underlines them.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<title>contains demo</title>

<script src="https://code.jquery.com/jquery-3.7.0.js"></script>

<div>Malcom John Sinclair</div>

$( "div:contains('John')" ).css( "text-decoration", "underline" );

Demo:

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    We will learn how to find an element using jQuery’s API. This article requires some knowledge of HTML, CSS, JavaScript, Bootstrap, and jQuery. The elements can be selected based on whether they contain the string we want to find. This can be done using the jQuery contains selector to select elements that contain the string.

    About contains selector

    Depending on the element, the matching text can appear directly within or within a descendant of the selected element. The :contains() selector in jQuery is used to select elements containing the specified string. The text must have a matching case to be selected.  

    Syntax: A string of text to look for. It’s case-sensitive.

    jQuery(":contains(text)")

    Approach:

    • Create an HTML file “index.html” in your local system.
    • Follow the basic HTML template and two-paragraph by adding the text inside the <p> tag.
    • Select the <p> tag with contains selector and pass the keyword that you want to select as a parameter in contains selector method.
    • After you successfully follow the above steps then attach a CSS property to that selected paragraph which contains the keyword that you pass as an argument in the contains method.

    Example: In this case, we are looking for the element that contains the word “Gfg”. We change the color of the particular paragraph that contains the word “Gfg” after selecting the element.

    HTML

    <!DOCTYPE html>

    <html>

    <head>

        <link href=

            rel="stylesheet" integrity=

    "sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"

            crossorigin="anonymous">

        <script src=

        </script>

        <style>

            body {

                border: 2px solid green;

                min-height: 240px;

            }

            .center {

                display: flex;

                justify-content: center;

            }

            h1 {

                color: green;

                text-align: center;

            }

        </style>

    </head>

    <body>

        <h1>GeeksforGeeks</h1>

        <div class="row container">

            <div class="col">

                <p>

                    Web development refers to the building, 

                    creating, and maintaining of websites.

                    Gfg includes aspects such as web design,

                    web publishing, web programming, and 

                    database management. It is the creation 

                    of an application that works over the 

                    internet i.e. websites.

                </p>

            </div>

            <div class="col">

                <p>

                    Web development refers to the building, 

                    creating, and maintaining of websites.

                    It includes aspects such as web design, 

                    web publishing, web programming, and 

                    database management. It is the creation 

                    of an application that works over the 

                    internet i.e. websites.

                </p>

            </div>

        </div>

        <script>

            $('p:contains("Gfg")').css({ 'color': 'green' });

        </script>

    </body>

    </html>

    Output:

    contains text

    Last Updated :
    01 Oct, 2021

    Like Article

    Save Article

    Последнее обновление Сен 22, 2021

    При создании сайтов а именно при написании скриптов веб разработчики часто сталкиваются с необходимостью найти определенный текст, а если быть точнее то найти блок с определенным текстом. В данном примере мы разберем как именно можно найти блок с текстом и произвести с ним определенные манипуляции.

    Задача

    Необходимо найти блок с текстом “featured”и удалить span блок который следует за родительским элементом нашего блока (с текстом). Затем удалить сам блок с текстом.

    JS готовый скрипт

        jQuery(document).ready(function($){
            $('span.tg-cats-holder').each(function(){
                $(this).find('span.tg-item-term:contains("featured")').closest('a.product_visibility').next('span:contains(",")').remove();
                $(this).find('span.tg-item-term:contains("featured")').closest('a.product_visibility').remove();
            });
        });

    Описание логики скрипта

    Для решения данной задачи перебираем каждый (ну в данном примере я так решил) родительский блок в котором находятся все наши блоки с которыми необходимо произвести все манипуляции – в моем примере это блок “span.tg-cats-holder”. Перебор мы производим при помощи .each.

    $('span.tg-cats-holder').each(function(){

    Далее в функции ищем наш блок с текстом, за содержащийся в блоке текст отвечает:

    После того как блок с текстом был найден переходим к родительскому блоку при помощи .closest:

    .closest('a.product_visibility')

    После перехода, находим находящийся рядом с родительским блоком span содержащий “|” и удаляем его:

    .next('span:contains("|")').remove();

    Далее, при помощи .remove() происходит удаление и самого блока.

    Пример на CodePen.io

    Источник записи:

    The :contains() is a jQuery selector that allows us to search text within the element and select it and perform an action on it.

    For example – you are dynamically listing records from the MySQL database table here, you have a requirement to add a search filter based on keypress. In case you can use jQuery AJAX which requests and load data from the server every time when the user press key in the search field.

    You can simplify this with :contains() jQuery selector to filter data on the Client side.

    There are some other ways in jQuery by which you can do the same operation. But, in this tutorial, I explain how you can use :contains() selector for search text.

    Note – The :contains() by default performs case-sensitive search. In the example, I show how you can use for case-sensitive and case-insensitive search.

    jQuery - Search text in the Element with :contains() Selector


    Contents

    1. :contains()
    2. Layout
    3. Search Text in Container
    4. With specific class in Container
    5. Case-insensitive
    6. Conclusion

    It selects the element which contains the specified value.

    Syntax –

    $(  ":contains( 'search text' )" );

    Example 

    $( "div:contains( 'hello' )" )

    2. Layout

    I have created post list where the input field is for search text and the <div class='content'> element which contains <div class='title'> and a <p> element.

    Completed Code

    <div class='container'>
    
     <!-- Search control -->
     <div>
      <input type='text' id='search' placeholder='Search Text'>
     </div>
    
     <!-- Content list -->
     <div class='content'>
      <div class='title'>
       <a href='https://makitweb.com/dynamically-add-and-remove-element-with-jquery/' >
         Dynamically add and remove element with jQuery
       </a> 
      </div>
      <p>In this post, I show how you can add and remove new element within your web page with jQuery...</p>
     </div>
    
     <div class='content'>
      <div class='title'>
        <a href='https://makitweb.com/how-to-delete-value-from-array-in-javascript/'>
         How to Delete a value from an Array in JavaScript
        </a>
      </div>
      <p>There are many cases when we have to remove some unused values from the Array which no longer needed within the program...</p>
     </div>
    
     <div class='content'>
      <div class='title'><a href='https://makitweb.com/read-and-get-parameters-from-url-with-javascript/'>Read and Get Parameters from URL with JavaScript</a></div>
      <p>If you are familiar with PHP where for reading parameters from URL you can use either $_GET or $_REQUEST which take the name of the argument and return value of it...</p>
     </div>
    
     <div class='content'>
      <div class='title'>
       <a href='https://makitweb.com/html-how-to-show-text-above-image-on-hover/'>
        HTML – How to Show Text Above Image on Hover
       </a>
      </div>
      <p>In this quick tutorial, I show How you can show text above Image when the user hovers the image using only HTML and CSS, no jQuery and JavaScript...</p>
     </div>
     
    </div>

    3. Search Text in Container

    The first start with a basic example, where I search input text within the <div class='content'> container if the text is available then show otherwise hide containers.

    Completed Code

    $(document).ready(function(){
     $('#search').keyup(function(){
     
      // Search text
      var text = $(this).val();
     
      // Hide all content class element
      $('.content').hide();
    
      // Search and show
      $('.content:contains("'+text+'")').show();
     
     });
    });

    View Demo


    4. With specific element in Container

    Now search for child elements with the specific class.

    Completed Code

    $(document).ready(function(){
     $('#search').keyup(function(){
     
      // Search text
      var text = $(this).val();
     
      // Hide all content class element
      $('.content').hide();
    
      // Search 
      $('.content .title:contains("'+text+'")').closest('.content').show();
     
     });
    });

    The above code searches the input value in title class if it finds then show the parent container.

    View Demo


    5. Case-insensitive

    # Example 1

    $(document).ready(function(){
     $('#search').keyup(function(){
     
      // Search text
      var text = $(this).val();
     
      // Hide all content class element
      $('.content').hide();
    
      // Search 
      $('.content .title:contains("'+text+'")').closest('.content').show();
     
     });
    });
    
    $.expr[":"].contains = $.expr.createPseudo(function(arg) {
      return function( elem ) {
       return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
      };
    });

    # Example 2

    Loop all .content class and search text with indexOf().

    $(document).ready(function(){
      $('#search').keyup(function(){
     
       // Search text
       var text = $(this).val().toLowerCase();
     
       // Hide all content class element
       $('.content').hide();
    
       // Search 
       $('.content .title').each(function(){
     
        if($(this).text().toLowerCase().indexOf(""+text+"") != -1 ){
         $(this).closest('.content').show();
        }
      });
     });
    });

    Both give the same output –

    View Demo


    6. Conclusion

    This makes your selection process little easier if you are searching for value in the element and want to take action on it like – update CSS style, add or remove CSS class, remove elements.

    If you found this tutorial helpful then don’t forget to share.

    Добавить комментарий