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
Add a ment  | 

5 Answers 5

Reset to default 6

You 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