简体   繁体   中英

how to select divs having exactly a specific text

In the example below I need 1 as the result because only one title has its text = lorem ipsum
I tried with contains but it counts all variations of a given criteria.

 var str = 'lorem ipsum'; let x = $(`.title:contains("${str}")`).length; console.log(x);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title'>lorem ipsum</div> <div class='title'>lorem ipsum a</div> <div class='title'>a lorem ipsum</div>

You can use .filter on the output of your selector to restrict it to the div that has the exact text contents of lorem ipsum .

 var str = 'lorem ipsum'; let x = $(`.title:contains("${str}")`).filter(function() { return $(this).text() == str; }).length; console.log(x);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title'>lorem ipsum</div> <div class='title'>lorem ipsum a</div> <div class='title'>a lorem ipsum</div>

Note that since you are testing the text value twice, you could just use $('.title') ; dependent on your HTML structure that may be faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM