javascriptpure-js

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>

Solution

  • 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

    <div class="class-category" id="fruits">
      <div class="class-container">
        <div class="class-controls">
          <button type="button" class="class-all" onclick="this.closest('.class-category').id">SELECT ALL</button>
        </div>
        <ul>
          <li><input type="checkbox" class="class-check" value="BANANA" onclick="this.closest('.class-category').id" />BANANA</li>
        </ul>
      </div>
    </div>
    <div class="class-category" id="animals">
      <div class="class-container">
        <div class="class-controls">
          <button type="button" class="class-all" onclick="this.closest('.class-category').id">SELECT ALL</button>
        </div>
        <ul>
          <li><input type="checkbox" class="class-check" value="DOG" onclick="this.closest('.class-category').id" />DOG</li>
        </ul>
      </div>
    </div>