[英]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
在下面的示例中,我需要1
作为结果,因为只有一个title
的 text = lorem ipsum
I tried with contains
but it counts all variations of a given criteria.我尝试使用contains
,但它会计算给定标准的所有变体。
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
.您可以在选择器的 output 上使用.filter
将其限制为具有lorem ipsum
确切文本内容的div
。
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')
;请注意,由于您要测试文本值两次,您可以只使用$('.title')
; dependent on your HTML structure that may be faster.取决于可能更快的 HTML 结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.