简体   繁体   中英

If child has an active class, add class to before anchor tag

I have a list and that contains sub menus with title anchor tags. And I just need to add class to its title anchor tag if dropdown menu li has an active class. Please take a look at this screenshot.

在此处输入图像描述

I easily do this by adding unique class to anchor tag and find that and add class. But what if I have more sub menus with title tag? Then I have to repeat my jQuery script again and again.

So I tried this way doing.

  $(document).ready(function () {
    if (jQuery(".dropdown li").hasClass("active")) {
        $(this).closest("a").addClass("main-link");.
    }
  });

But it's not working. Is there any way to do this?

Here is the fiddle

.closest() finds the closest containing element that matches the selector. The a is not a container of the dropdown, it's the element before the dropdown. For that you need to use .prev() .

You also shouldn't be using if and this . if doesn't bind this to the elements where the condition succeeds. Just use a selector and DOM navigation from that.

 $(document).ready(function() { $(".dropdown:contains(li.active)").prev("a").addClass("main-link"); });

Closest looks at parents, the anchor is not a parent. Plenty of ways to walk the tree

 $("li.active").parent().closest("li").find(">a").addClass("foo"); $("li:has(> ul > li.active)").find(">a").addClass("bar");
 .foo { background-color: yellow; }.bar { color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li> <a>A</a> <ul> <li class="active">X</li> </ul> </li> </ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM