I’m trying to add a Class to each anchor inside #somecontainer whose children have .someclass
For example.
<div id="container">
<a><span class="someclass"></span></a>
<a></a>
<a><span class="someclass">/span></a>
</div>
In the above code i want the first and third anchors to have a class ‘.anotherclass’
I tried this code but it doesn’t seem to work
jQuery('#container a').each(function(){
jQuery(this).has('.someclass').addClass('anotherclass');
})
Update:
.has()returns abooleanand not jQuery object. That’s why the
code didn’t work
I suspect your problem stems from the fact that your HTML is malformed, i.e. you need to close your spans.
Additionally, your code can be simplified a bit by using
:hasto select only anchors that contain an element matching your desired class name:i.e. “select all anchors that are descendants of an element with ID
containerand that have a descendant with classsomeclass“As Jon has pointed out, an alternative is to use a basic selector, then filter the resulting collection using a custom function:
The function needs to return
truefor any element that you want to retain, andfalsefor any element you don’t.