jQuery addClass to each element that has children with '.class'
Solution 1
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.
Solution 2
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.
Solution 3
jQuery('#container a .someclass').parent().addClass('anotherclass');
rzr
Updated on July 18, 2022Comments
-
rzr almost 2 years
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 -
John Dvorak over 11 yearsthis will add the class to the
span
. This is not the desire. -
Asad Saeeduddin over 11 years@Jon Do you mean for it to be used with a selector or a function?
-
Asad Saeeduddin over 11 years@JanDvorak I suspect it is because his HTML is malformed (unclosed spans)
-
John Dvorak over 11 years@Asad then I believe this will break under the same circumstances.
-
Waihon Yew over 11 years@Asad: With a function, mainly for when selectors won't cut it.
-
rzr over 11 yearsThat code is just an example. The actual code doesn't have unclosed tags.
-
rzr over 11 yearsanyway, this code works like charm. still wondering why my code doesn't work.
-
Asad Saeeduddin over 11 years@JanDvorak Yes, I've mentioned this in the answer.
-
Asad Saeeduddin over 11 years@Jon I've added a mention of
filter
to the answer. Thanks.