Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 632
rzr Avatar asked Dec 05 '12 12:12

rzr


3 Answers

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.

like image 84
Asad Saeeduddin Avatar answered Nov 15 '22 21:11

Asad Saeeduddin


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.

like image 45
Chamila Chulatunga Avatar answered Nov 15 '22 22:11

Chamila Chulatunga


jQuery('#container a .someclass').parent().addClass('anotherclass');​
like image 33
Jayne Mast Avatar answered Nov 15 '22 22:11

Jayne Mast