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 aboolean
and 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.
<div id="container">
<a><span class="someclass"></span></a>
<a></a>
<a><span class="someclass"></span></a>
</div>
Additionally, your code can be simplified a bit by using :has
to select only anchors that contain an element matching your desired class name:
$('#container a:has(.someclass)').addClass('anotherclass');
i.e. "select all anchors that are descendants of an element with ID container
and that have a descendant with class someclass
"
As Jon has pointed out, an alternative is to use a basic selector, then filter the resulting collection using a custom function:
$('#container a').filter(function(){
return $(this).has('.someclass').length > 0
}).each(function(){
$(this).addClass('anotherclass');
});
The function needs to return true
for any element that you want to retain, and false
for any element you don't.
Try:
$('#container a .someclass').parents('a').addClass('anotherClass');
Basically we work our way right down to find the elements with the class 'someclass': $('#container a .someclass')
, and then from there work our way back up to the enclosing anchor: .parents('a')
, which is where the class 'anotherclass' needs to be added.
jQuery('#container a .someclass').parent().addClass('anotherclass');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With