简体   繁体   中英

jquery onclick toggle nearest UL

Trying to toggleClass the nearest #dropdown element using jQuery and I can't seem to find the ul. jQuery is loading fine and each element acknowledges the click.

HTML code is:

<li onclick="showDropDown()" class="filter-button">
                            Filter by <strong>Aread</strong> +
    <ul id="dropdown" class="dropdown-content">
      <li><a href="">Test 1</a></li>
      <li><a href="">Test 3</a></li>
      <li><a href="">Test 2</a></li>
    </ul>
</li>

jQuery code is:

  function showDropDown() {
    jQuery(this).parents("li").find("ul").toggleClass('show');
  }

dropdown ul is the child element of filter-button li. So you dont need to find the parent here

$(".filter-button").click(function() {
  $(this).find("ul").toggleClass('show');
});

OR,

If you really need to use the inline method calling then you need to pass the current object as well,

<li onclick="showDropDown(this)" class="filter-button">

code,

function showDropDown(obj) {
  jQuery(obj).find("ul").toggleClass('show');
}

You were missing this object in the method call.

Refer the demo here .

Please find the code below:

HTML:

<ul>
  <li onclick="showDropDown(this)" class="filter-button">
    Filter by <strong>Aread</strong> +
    <ul id="dropdown" class="dropdown-content">
      <li><a href="">Test 1</a></li>
      <li><a href="">Test 3</a></li>
      <li><a href="">Test 2</a></li>
    </ul>
  </li>
</ul>

JS:

function showDropDown(obj) {
  $(obj).find("ul").toggle();
}

If there are many UL elements as child and nextSibling, you have to write as below.

demo : https://jsfiddle.net/nigayo/Lo3yf31y/1/

[JavaScript]

      $(".filter-button").click(function() {
        $(this).find("ul:first").toggleClass('show');
        $(this).next("ul:first").toggleClass('show');
      });

[HTML]

  <li class="filter-button">
    Filter by <strong>Aread</strong> +
    <ul id="dropdown" class="dropdown-content">
      <li><a href="">Test 2</a></li>
    </ul>

    <ul id="dropdown2" class="dropdown-content">
      <li><a href="">Test 2</a></li>
    </ul>
  </li>

  <ul id="dropdown_next" class="dropdown-content">
      <li><a href="">Test 2</a></li>
  </ul>
  <ul id="dropdown_next2" class="dropdown-content">
    <li><a href="">Test 2</a></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