0

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?

1
  • I don't really understand your criteria. Can you rephrase/explain? Commented Jul 24, 2009 at 13:26

4 Answers 4

3

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');
Sign up to request clarification or add additional context in comments.

2 Comments

referring to tvanfosson's reply here, if i add class "active" to an element that has class active already will it cause any problems?
It hasn't added duplicates when I used similar logic.
0

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');

Comments

0

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)').

Comments

0
//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');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.