Wilson
Wilson

Reputation: 8768

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.

Upvotes: 4

Views: 1578

Answers (3)

Austin
Austin

Reputation: 6034

The contains selector

Since you are alread using jQuery, you can take advantage of its .contains method or the ':contains' pseudo-selector:

$("#word span").contains("word")

OR

$("#word span:contains(word)")

This would not return true for each span that contains the word, but rather the elements that contain that word. You would be left with a list of matched elements, that can be manipulated like so:

var $matched = $("word span").contains("word");

$matched.each(function (i, el) {
    // do something with the el
});

Reference

http://api.jquery.com/jQuery.contains/

Upvotes: 2

Ram
Ram

Reputation: 144689

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;

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191749

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++;
   }
});

Upvotes: 4

Related Questions