my question is that I want to create event on Edit Button but do not know how to listen event happened on any of edit button by add Event Listener method so that I can edit my list item
-
2Does this answer your question? [How to find event listeners on a DOM node when debugging or from the JavaScript code?](https://stackoverflow.com/questions/446892/how-to-find-event-listeners-on-a-dom-node-when-debugging-or-from-the-javascript) – willwrighteng Jan 03 '21 at 04:22
1 Answers
When a DOM event handler is triggered, it is automatically passed a reference to the event object for that event. Also, within the handler, the this
keyword is bound to the DOM object that is handling the event. If the DOM object that is handling the event is not the same one that actually triggered the event in the first place (because you are handling the event at an element higher up in the DOM structure due to bubbling), you can still get a reference to the element that triggered the event with event.target
. Knowing these things allows you to access surrounding elements without knowing their specific id
(or even having id
s in the first place.
The following example leverages "event bubbling" where we only set up one handler at a DOM element that is an ancestor of all the elements that might trigger the event. When any of these elements triggers the event, it will bubble up to the ancestor and be handled there. Then, within that handler, we access the original element that triggered the event with event.target
and work from there.
// set up a handler on an ancestor of all the
// elements that could trigger the event
document.querySelector(".wrapper").addEventListener("click", function(event){
console.clear();
console.log("The object handling the event is: " + this.nodeName + "#" + this.id);
// Get a reference to the actual element that triggered the event
const target = event.target;
console.log("You clicked the " + target.textContent + " button");
// We can now access other elements, relative to the target
const prevSib = target.previousElementSibling;
console.log("The textbox associated with the button you clicked was: " + prevSib.id);
prevSib.value = "Winner!";
});
<div class="wrapper" id="wrapper">
<div><input id="One"><button>Edit 1</button></div>
<div><input id="Two"><button>Edit 2</button></div>
<div><input id="Three"><button>Edit 3</button></div>
<div><input id="Four"><button>Edit 4</button></div>
<div><input id="Five"><button>Edit 5</button></div>
</div>

- 64,069
- 6
- 49
- 71