Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if any tags have a certain inner HTML

How would i write a jquery function that returns true if any spans within a div with id 'word' have an inner HTML of value v? For the selector, I have:

$('#word span').html()

I'm confused as to the correct way to iterate through them, and return a boolean value because currently i have 5 span tags within that div.

like image 481
Wilson Avatar asked Feb 18 '23 01:02

Wilson


2 Answers

You could use :contains as in $("#word span:contains(v)"), but that selects spans that contain 'v' rather than have it as an exact value. .html only returns the html string of the first element selected, so you probably want to iterate with .each and do an exact comparison:

var count = 0;
$("#word span").each(function () {
   if ($.trim($(this).text()) === 'v') {
      count++;
   }
});
like image 91
Explosion Pills Avatar answered Feb 21 '23 03:02

Explosion Pills


You can use filter method:

$("#word span").filter(function () {
      return this.innerHTML === v; // in case that v is a variable
      // return $(this).text() === 'v';  
}).length;
like image 33
undefined Avatar answered Feb 21 '23 02:02

undefined