I have a couple of h2’s. Some of them have spans inside, some don’t. I would like to add a class to those who has not.
I tried this:
$('h2').each(function(){
if($(this).not(':has(span)')){
$(this).addClass('font-size');
} else {
$(this).removeClass('font-size');
}
});
and this:
if($('h2').not(':has(span)')){
$(this).addClass('font-size');
} else {
$(this).removeClass('font-size');
}
But what this seem to do is add ‘font-size’ to all h2’s if one or more of them has spans inside.
You can use the filter method . Something like this:
// Look at all h2's
var $withSpans = $('h2').filter(function(){
// If it has at least one span, save it
if($('span', $(this)).length)
return true
// Otherwise remove it from the selector
else
return false
})
// Finally, add the class
$withSpans.addClass('font-size')
Or more succinctly:
$('h2').filter(function(){
return $('span', $(this)).length
}).addClass('font-size')
1 Like
Thanks worked perfect, and i learned about .filter() =)
system
Closed
April 9, 2015, 3:12am
4
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.