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 >
<span ><%= task.taskDescription %></span>
(this-form)=> <form action="/edit" method="POST" >
<input type="text" name="taskDescription" />
<input type="hidden" name="id" value="<%-task._id%>" />
</form>
<div >
(this-btn)=> <button >Edit</button>
<form action="/delete" method="POST">
<input type="hidden" name="id" value="<%-task._id%>" />
<input type="submit" name="submit" value="Delete" />
</form>
</div>
</li>
CodePudding user response:
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:
- start from
this
(the button clicked) - Go up to the parent of the DOM element twice (first to
<div >
then to the<li ...>
element) - From there we select the
<form ...>
element.