zok
zok

Reputation: 7902

Check for element with given class, case not found, add class to first element

How do you do that:

On a set of elements, check if there's any with a given class. Case not found, add the class to the first element of the set.

I came up with the code below.

It works well, but, is there a simpler/cleaner/cleverer way to do it?

var noActiveElement = true;

$('.list-group-item').each(function(){
     if ($(this).hasClass('active')){
         noActiveElement = false;
         return false;
     }                    
 });

  if (noActiveElement)
     $('.list-group-item').eq(0).addClass('active');

Upvotes: 0

Views: 59

Answers (2)

user3274902
user3274902

Reputation: 35

if (!$('.list-group-item.active').length) {
  $('.list-group-item').eq(0).addClass('active');
}

Upvotes: 0

charlietfl
charlietfl

Reputation: 171690

testing length of elements found by selector is about the simplest way

if( !$('.list-group-item.active').length ){
  $('.list-group-item').eq(0).addClass('active');
}

When you use $(selector) an array of elements matching the selector is created. If none found the length of array is zero

Upvotes: 4

Related Questions