Duke
Duke

Reputation: 229

find all elements and if don't have the class, add other class use jQuery

var $trs = $("#task-list-tbody").find("tr");

$.each($trs, function(index, item){
  if(!item.hasClass("tGroup")){
    item.addClass("subgroup");
  }
});

this is failed,how can I do? I just want to add subgroup class if the tr elements has no tGroup class

Upvotes: 0

Views: 138

Answers (3)

Praveen
Praveen

Reputation: 56509

Your code is suffering

Object #<HTMLTableRowElement> has no method 'hasClass'

So enclose item with $() because when you iterate the trs, it will returns individual items a html <tr>..</tr>.

Finally,

$.each($trs, function(index, item){
  if(!$(item).hasClass("tGroup")){
        $(item).addClass("subgroup");
  }
});

Upvotes: 1

Aur&#233;lien Gasser
Aur&#233;lien Gasser

Reputation: 3120

A shorter version

$("#task-list-tbody").find("tr:not(.tGroup)").addClass('subgroup');

Upvotes: 4

Ringo
Ringo

Reputation: 3965

Try this:

var $trs = $("#task-list-tbody").find("tr");

$trs.each(function(){
   if($(this).attr('class').indexOf('tGroup') == -1){
      $(this).addClass('subgroup');
   }
});

Upvotes: 0

Related Questions