Search code examples
jquerynavigationparent

Add class to parent li if it has a sub ul - using jquery


I'd like to be able to add a class to my top most li, but only if it has a sub ul or ul ul. Each li contains a link and yes, it's a drop down navigation menu.

My current jquery:

$(function() {
    $('ul.sub-menu').hide();
    $('.sub-menu ul').hide();

    $('#menu-navigation li').hover(function(){
        $(this).children('ul').slideDown("fast");
        },
    function(){
        $(this).children('ul').hide();
    });

    $('#menu-navigation ul li').hover(function(){
        $(this).children('ul').slideDown("fast");
        },
    function(){
        $(this).children('ul').hide();
    });
});

This only shows / hides each element.

I'd like the top-most li to have a class, so that when I hover over the child elements, that class remains in place. How would I do this?

Thanks in advance for any help.


Solution

  • Try this

    $(function() {
        $('ul.sub-menu').hide();
        $('.sub-menu ul').hide();
    
        $('#menu-navigation li').hover(function(){
            $(this).children('ul').slideDown("fast");
            },
        function(){
            $(this).children('ul').hide();
        });
    
        $('#menu-navigation > ul > li').hover(function(){
            $(this).children('ul').slideDown("fast");
        },
        function(){
            $(this).children('ul').hide();
        });
    });