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/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745281209a4620288.html
评论列表(0条)