javascript - Check if any tags have a certain inner HTML - Stack Overflow

How would i write a jquery function that returns true if any spans within a div with id 'word'

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.

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.

Share Improve this question asked Dec 27, 2012 at 20:25 WilsonWilson 8,78820 gold badges72 silver badges102 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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 parison:

var count = 0;
$("#word span").each(function () {
   if ($.trim($(this).text()) === 'v') {
      count++;
   }
});

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;

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./jQuery.contains/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745281209a4620288.html

相关推荐

  • javascript - Check if any tags have a certain inner HTML - Stack Overflow

    How would i write a jquery function that returns true if any spans within a div with id 'word'

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信