Question

I'm building a site with some software that spits out a set of hierarchically nested lists that I'm in turn using the superfish jquery plugin to turn into drop-down menus.

The issue that I have is that said software will only apply one active class (to whichever page/element is active at the time) - if I'm on a second-level page and I need to apply one to the parent

  • tag as well, in order for the menus to stay open. I don't want to hack the core for obvious reasons, so I'm wondering if I can use Jquery to apply some simple magic.

    Is there a way of targetting the parent li element of a list that contains a class='active'? (and not if I'm only in a top-level page, so don't need to traverse upwards)

    For example the code that the software generates is like this:

    <ul>
       <li><a href="#">First level</a>
         <ul>
             <li class="active"><a href="#">Second 1</li>
             <li><a href="#">Second 2</li>
             <li><a href="#">Second 3</li>
          </ul>
       </li>
    </ul>
    

    I need to apply another class="active" to the top-level <li> as well because it's the parent of the active node.

    Does that make sense?

  • Was it helpful?

    Solution

    Try this

    var $this;
    $("ul > li").each(function(){
        $this = $(this);
    
        if($this.find("> li.active").length)
          $this.addClass("active");
    }
    
    Licensed under: CC-BY-SA with attribution
    Not affiliated with StackOverflow
    scroll top