Reputation: 7902
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
Reputation: 35
if (!$('.list-group-item.active').length) {
$('.list-group-item').eq(0).addClass('active');
}
Upvotes: 0
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