jQuery addClass to each element that has children with '.class'
Asked Answered
O

3

8

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 a boolean and not jQuery object. That's why the code didn't work

Occur answered 5/12, 2012 at 12:21 Comment(0)
M
14

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.

Malaria answered 5/12, 2012 at 12:23 Comment(8)
@Jon Do you mean for it to be used with a selector or a function?Malaria
@JanDvorak I suspect it is because his HTML is malformed (unclosed spans)Malaria
@Asad then I believe this will break under the same circumstances.Luettaluevano
@Asad: With a function, mainly for when selectors won't cut it.Koroseal
That code is just an example. The actual code doesn't have unclosed tags.Occur
anyway, this code works like charm. still wondering why my code doesn't work.Occur
@JanDvorak Yes, I've mentioned this in the answer.Malaria
@Koroseal I've added a mention of filter to the answer. Thanks.Malaria
V
4

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.

Victory answered 5/12, 2012 at 12:31 Comment(0)
V
2
jQuery('#container a .someclass').parent().addClass('anotherclass');​
Varus answered 5/12, 2012 at 12:26 Comment(1)
this will add the class to the span. This is not the desire.Luettaluevano

© 2022 - 2024 — McMap. All rights reserved.