PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

[FIXED] how to select element from the sibling's child element javascript (ANSWERED)

 August 13, 2022     dom, ejs, html, javascript     No comments   

Issue

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.


Answered By - arcyqwerty
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing