admin管理员组文章数量:1392002
I have a group of rows selected and I am now trying to determine whether or not they contain a specific class.
I have tried it with hasClass
without success as well as with find
:
var group = $('table').find('[data-group="group1"]');
//this doesn't work, it always enters in the condition
if(group.find('.active')){
alert("Founded?");
group.addClass('green');
}
/
I have also tried it with if(group.find('.active').length)
but still not getting the correct result:
/
I have a group of rows selected and I am now trying to determine whether or not they contain a specific class.
I have tried it with hasClass
without success as well as with find
:
var group = $('table').find('[data-group="group1"]');
//this doesn't work, it always enters in the condition
if(group.find('.active')){
alert("Founded?");
group.addClass('green');
}
http://jsfiddle/kAHyA/1/
I have also tried it with if(group.find('.active').length)
but still not getting the correct result:
http://jsfiddle/kAHyA/3/
Share Improve this question asked Jun 17, 2013 at 15:42 AlvaroAlvaro 41.6k31 gold badges172 silver badges348 bronze badges 1-
1
Why did
hasClass
not work? – Bergi Commented Jun 17, 2013 at 15:49
5 Answers
Reset to default 6You can do this with hasClass method http://api.jquery./hasClass/
if(group.hasClass('active')){
...
}
If you tried this :
if(group.hasClass('.active')){
...
}
It certainly won't work, note the difference with the "."
Try this,
if(group.filter('.active').length)
Just want to check if the tr has class active
and has the data attribute, so just a simple selector is enough.
var matches = $('table').find('.active[data-group="group1"]'); //This will give you all the trs with the attribute and class active.
if(matches.length > 0)
{
alert('Found Match');
matches.addClass('green');
}
if you just want to apply class directy just chain it through:
$('table').find('.active[data-group="group1"]').addClass('green');
Demo
You can do this -
if(group.is('.active')){
group.addClass('green');
}
demo --->
http://jsfiddle/kAHyA/6/
The problem with .find()
is that it will always return a jQuery object, which like any other object (other than null
) is truthy.
You want to check the length: if( group.find(".active").length > 0)
本文标签: javascriptCheck if a class exist within a group of selected elementsStack Overflow
版权声明:本文标题:javascript - Check if a class exist within a group of selected elements - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744700921a2620557.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论