MayThrow
MayThrow

Reputation: 2201

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

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

Upvotes: 8

Views: 41985

Answers (3)

user1726343
user1726343

Reputation:

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.

Upvotes: 14

Chamila Chulatunga
Chamila Chulatunga

Reputation: 4914

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.

Upvotes: 4

Jayne Mast
Jayne Mast

Reputation: 1487

jQuery('#container a .someclass').parent().addClass('anotherclass');​

Upvotes: 2

Related Questions