Question

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

Was it helpful?

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

OTHER TIPS

One possible way is to look for the closest ul.first_level in the first round, then use .siblings() to get the link itself (not making major modifications in your code, just changing the parts with the problem):

$("nav.menu>ul>li").children().click(function() {
    var item1 = $(this);
    var theLink = item1.closest('.first_level').siblings('.t2');

    theLink.addClass('font_red');
    return false;
});​

jsFiddle Demo

Another way:

$("nav.menu>ul>li").children().click(function(e) {
  e.preventDefault();
  $(this).parents('#nav>li:has(.t2)').find('>a').addClass('font_red');
});​
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top