Search code examples
jquerydom-traversal

children items when clicked change the parent color


I have a menu with multiple ul items. What i want is change the color of top menu text to red.

However this only works when i click in the first item, not in the children items.

For example, i want to click in hydrotherapy and change to red the word Services. The parent. Any idea?

$("nav.menu>ul>li").children().click(function() {
    alert("asd");
    var item1 = $(this),
        primeira_ul = item1.closest('.menu>ul#nav>li>a.t2');

    item1.addClass('font_red');
    return false;
});

demo


Solution

  • You can search for the first child of $(this) that is an a tag. Note that $(this) refers not to the event source, but the $("nav.menu>ul>li") element which is already your top level li.

    You probably also want to unset the siblings.

    $("nav.menu>ul>li").on("click", function() {
        var item1 = $(this),
            primeira_ul = item1.closest('.menu>ul#nav>li>a.t2');
    
        $(this).siblings().find("> a").removeClass('font_red');
        $(this).find("> a").first().addClass('font_red');
        return false;
    });
    

    JS Fiddle