0

I've got multiple elements with a common class. How do I check each element and add if the class isn't there?

This is what I did but not sure if it's the way to do it.

$(".common").each(function(){
     if (!$(this).hasClass("test")) {
       //do some
     }
};
Becky
  • 5,467
  • 9
  • 40
  • 73

2 Answers2

1

The much simpler way is to update your selector with :not() pseudo class selector.

$(".common:not(.test)").each(function(){
   //do some
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

There's no need, this will add the class to all .common elements if it is not there

$(".common").addClass("test");
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • Thanks. I know that addClass is the way to do it but checking if the `.each()` is correct. – Becky Sep 05 '16 at 08:28
  • @Becky The `.each` is pointless in this case. jQuery automatically iterates over every element which matches the selector when using `addClass` - that was my point. – Jamiec Sep 05 '16 at 08:34