children items when clicked change the parent color
-
15-07-2021 - |
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;
});
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;
});
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;
});
Another way:
$("nav.menu>ul>li").children().click(function(e) {
e.preventDefault();
$(this).parents('#nav>li:has(.t2)').find('>a').addClass('font_red');
});