kylex
kylex

Reputation: 14406

Display hidden li based on class

I have the following list structure:

<ul>
    <li>One</li>
    <li>Two
        <ul>
             <li class="active">Two-1</li>
             <li>Two-2</li>
        </ul>
    </li>
    <li>Three
        <ul>
            <li>Three-1</li>
        </ul>
    </li>
</ul>

with the following CSS:

ul li ul{
    display:none;
}
ul li:hover ul{
    display:block;
}

What I would like is this: When an li class is active, the entire structure down until the active class gets displayed.

so in the case provided the following would show, along with the top level:

I'd like either a CSS or jQuery implementation (or mixture of the two) if possible.

Upvotes: 3

Views: 1334

Answers (4)

Fabio
Fabio

Reputation: 1151

There are so many ways to achive this, i prefer the others posted in here but here are another two.

$('li.active').parent().css('display', 'block');
$('ul:parent').has('li.active').css('display', 'block');

They are more specific and will work only on 'lists'.

You can also use show() instead of css('display', 'block'). Its probly better coz once the element is hidden again they get back to its previous display value.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630637

You can show the active's parents using .parents() or :has() when the page loads like this:

$(function() {
  $('.active').parents().show();​​​​​​​​​
  //or..
  $(':has(.active)').show();​​​​​​​​​
});

Either of these work any number of levels deep, the first would be a bit faster though.

Upvotes: 4

cletus
cletus

Reputation: 625465

You can use the :has() selector for this:

$("ul:has(li.active)").show();

This selector finds any <ul> element that has a descendant <li> with a class of active.

Upvotes: 1

mVChr
mVChr

Reputation: 50215

Not sure from the way the question is phrased, but isn't this line of jQuery all you need?

​$('.active').parent().show().parent().parent().show();​​​​​​​​​

Upvotes: 1

Related Questions