qadenza
qadenza

Reputation: 9293

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>

Upvotes: 2

Views: 33

Answers (1)

Nick
Nick

Reputation: 147166

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.

Upvotes: 1

Related Questions