admin管理员组

文章数量:1320822

I have a dropdown menu and I want to verify if the submenu hasClass in, then for the closest ul that has class .menu add class in. Here is my code but it adds for all ul that has class .menu instead closest.

<script>
  if($(".submenu").hasClass( "in" )) {
    $(".submenu").closest(".menu").addClass("in");
  }
</script>

I have a dropdown menu and I want to verify if the submenu hasClass in, then for the closest ul that has class .menu add class in. Here is my code but it adds for all ul that has class .menu instead closest.

<script>
  if($(".submenu").hasClass( "in" )) {
    $(".submenu").closest(".menu").addClass("in");
  }
</script>
Share Improve this question edited May 18, 2017 at 19:08 max 8,6873 gold badges25 silver badges56 bronze badges asked May 18, 2017 at 19:05 chris227chris227 60711 silver badges32 bronze badges 5
  • Please post your HTML as well – j08691 Commented May 18, 2017 at 19:07
  • can you share html as well – Kiran Commented May 18, 2017 at 19:07
  • closest finds the closest parent. Edit: oops, I misread! – Frank Modica Commented May 18, 2017 at 19:07
  • 1 @FrankModica .closest() searches up the DOM through all ancestors of a given element, not just the parent – j08691 Commented May 18, 2017 at 19:08
  • @j08691 and the element itself. – max Commented May 18, 2017 at 19:09
Add a ment  | 

3 Answers 3

Reset to default 6

You need to change the selector

$(".submenu.in").closest(".menu").addClass("in");

Alternatively :has() selector can also be used as

Selects elements that contain at least one element that matches the specified selector.

$(".menu:has(.submenu.in)").addClass("in");

Try this:

For looking up the DOM use this:

<script>
    $('.submenu.in').closest('.menu').addClass("in");
</script>

For looking into the children elements use this:

<script>
    $('.submenu.in .menu').first().addClass("in");
</script>

I'm assuming you want to target a child element of .submenu so try this

<script>
  if($(".submenu").hasClass( "in" )) {
    $(".submenu").children(".menu").addClass("in");
  }
</script>

Or if you just want first level children here's a solution: How to select only the first level children in JQuery

本文标签: javascripthow to addClass to closest elementStack Overflow