admin管理员组文章数量:1418145
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 badges3 Answers
Reset to default 4You 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/
本文标签: javascriptCheck if any tags have a certain inner HTMLStack Overflow
版权声明:本文标题:javascript - Check if any tags have a certain inner HTML - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745281209a2651433.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论