简体   繁体   中英

pure JS - get parent DIV ID dynamically through the onlick event

How can I get the ID of each main DIV through the onclick event?

I need the element to be found without using static names in the onclick events like the example document.getElementById('fruits'); .
I wish there was a way to get to the ID of each top parent DIV fruits and animals in a more dynamic way without using IDs on the sub-DIVs.

<div id="fruits">

  <div class="class-container">
    <div class="class-controls">
      <button type="button" class="class-all" onclick="document.getElementById('fruits');">SELECT ALL</button>
    </div>

    <ul>
      <li><input type="checkbox" class="class-check" value="BANANA" onclick="document.getElementById('fruits');" />BANANA</li>
    </ul>
  </div>
  
</div>

<div id="animals">

  <div class="class-container">
    <div class="class-controls">
      <button type="button" class="class-all" onclick="document.getElementById('animals');">SELECT AL</button>
    </div>

    <ul>
      <li><input type="checkbox"class="class-check" value="DOG" onclick="document.getElementById('animals');" />DOG</li>
    </ul>
  </div>
  
</div>

I would use el.closest , with el being the item you clicked. You can add class to the parent element something like class="category" and then el.closest('.category').id .

You can check more at https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

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