0

When I click on open it toggles all of the submenus. I want to toggle only the exact ul under the li.

$(document).ready(function(){
    $(".has-children>a").click(function(event){
        event.preventDefault();
    });
    $('.has-children').click(function() {
        $(this).find('>ul').toggle(300);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
    <li class="has-children">
    <a href="#">open</a>
        <ul class="submenu" style="display:none">
            <li class="has-children">
            <a href="#">open</a>
                <ul class="submenu" style="display:none">
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                </ul>
            </li>
        </ul>

    </li>
</ul>

1
  • Try adding an id to that one and then use it Commented Jan 19, 2018 at 8:31

1 Answer 1

2

You can achieve this by changing find() to children() to target only direct children of the li.

$(document).ready(function(){
    $(".has-children>a").click(function(event){
        event.preventDefault();
    });
    $('.has-children').click(function() {
        $(this).children('ul').toggle(300);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
    <li class="has-children">
    <a href="#">open</a>
        <ul class="submenu" style="display:none">
            <li class="has-children">
            <a href="#">open</a>
                <ul class="submenu" style="display:none">
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                </ul>
            </li>
        </ul>

    </li>
</ul>

This however causes a problem where clicking on children of children will close the menu, so instead you can use a tag and the jQuery next() function to toggle instead of children() or find() like this:

$(document).ready(function() {
  $(".has-children>a").click(function(event) {
    event.preventDefault();
    $(this).next().toggle(300);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
  <li class="has-children">
    <a href="#">open</a>
    <ul class="submenu" style="display:none">
      <li class="has-children">
        <a href="#">open</a>
        <ul class="submenu" style="display:none">
          <li>1</li>
          <li>2</li>
          <li>3</li>
        </ul>
      </li>
    </ul>

  </li>
</ul>

This also makes your script much shorter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.