Donnie
Donnie

Reputation: 373

Add class to parent tag if parent has some class

I have a some jQuery code:

jQuery('li:has(.selected)').addClass('test');

and I need to add class to li if li has a with class .selected.

Upvotes: 1

Views: 1054

Answers (2)

Alex
Alex

Reputation: 10216

Try this:

$(function() {
    $('li').has('a.selected').addClass('test');
});

http://api.jquery.com/has/

Another easy thing would be to just select the a itself:

$(function() {
    $('a.selected').parent('li').addClass('test');
});

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074038

I need to add class to LI if LI has A with class .selected

So the li will have an a.selected in it? Then:

jQuery("a.selected").parent("li").addClass("test");

or possibly

jQuery("li > a.selected").parent().addClass("test");

or if you really mean ancestor, not parent:

jQuery("li a.selected").closest('li').addClass("test");

More:

Upvotes: 3

Related Questions