Search code examples
javascripthtmldomejs

How to select element from the sibling's child element javascript


I want to select a form by clicking a button that is a child of the form sibling parent.. i know it's confusing.

<li class="list-group-item d-flex justify-content-between align-items-center task">
      <span class="task"><%= task.taskDescription %></span>
      (this-form)=> <form action="/edit" method="POST" class="hidden edit-form">
        <input type="text" name="taskDescription" />
        <input type="hidden" name="id" value="<%-task._id%>" />
      </form>
      <div class="btns">
        (this-btn)=> <button class="edit">Edit</button>
        <form action="/delete" method="POST">
          <input type="hidden" class="edit" name="id" value="<%-task._id%>" />
          <input type="submit" name="submit" value="Delete" />
        </form>
      </div>
    </li>

Solution

  • You can select the form directly using any unique selector. An id might be best, but in the example given, you could use document.querySelector('.edit-form').

    If there's multiple similar elements and you want to be sure to get the one with the common parent from the button's onclick handler:

    function onclick() {
      const form = this.parentNode.parentNode.querySelector('.edit-form');
      // do what you want with form here
    }
    

    What it does is:

    1. start from this (the button clicked)
    2. Go up to the parent of the DOM element twice (first to <div class="btns"> then to the <li ...> element)
    3. From there we select the <form class="edit-form ..." ...> element.