tags:

views:

90

answers:

4

with the markup like:

<ul>
    <li><a href="#">Link 1</a></li>
    <li>
        <a href="#">Link 2</a>
        <ul>
            <li><a href="#" class="active">Link 2.1</a></li>
            <li><a href="#">Link 2.2</a></li>
        </ul>
    </li>
</ul>

i want to add a class "active" to , Link 2 (line 4), or links that have inner a.active links. how can i do it with jquery or even pure css?

A: 

One way assuming the top level ul has an id of yourUl:

$('#yourUl>li>a').filter( function(){
    return $(this).find('a.active').length;
} ).addClass('active');
redsquare
A: 

It's a bit tricky to do this in the general case since it highly depends on markup, but it looks like what you want is to change the class of an anchor any of whose next siblings contains an anchor with class active. The following should do the trick, with the slight optimization that it will skip any anchors that are already so marked. It uses the nextAll() method and :not, and :has selectors.

 $('a:not(.active)').nextAll(':has(a.active)')
                    .addClass('active');

If you need the initial anchor restricted to a certain level, just change the initial selector so that it is specific to the level that you need. The easiest way is to base it off a particular element $('#myList > a:not(.active)') or with a particular class $('a.topLevel:not(.active)').

tvanfosson
A: 
//adds active to second anchor
$('ul>li>a:eq(2)').addClass('active');

//adds active to anything with an active link as a descendant
$('ul>li>a').each(function(i) {
    if( $('a.active', this ).length > 0 )
        $(this).addClass('active');
});
geowa4
+3  A: 

Using the ":has" operator, you can make this a lot simpler. This line grabs any "li" element containing a "li" with an active link.

$('li:has(li>a.active)').addClass('active');
John Fisher
referring to tvanfosson's reply here, if i add class "active" to an element that has class active already will it cause any problems?
iceangel89
It hasn't added duplicates when I used similar logic.
John Fisher