There are a couple of ways to go about this, but in all scenarios you really should not use inline event handling attributes (onclick
). There are many reasons not to use this 20+ year old technique that just will not die the death it deserved to almost 10 years ago. Additionally, don't use .innerHTML
to get/set values that don't contain any HTML as it is wasteful, in terms of performance and it opens up security holes in your application. Instead, use .textContent
to get/set non-HTML values.
For each element to have its own handler:
- Get all the elements that need a similar handler into an array
- Loop over the array
- Assign a handler to the current array element
// Get all the elements that need the same handler into an Array
let divs = Array.prototype.slice.call(document.querySelectorAll("div"));
// Iterate the array
divs.forEach(function(div){
// Set up the handler
div.addEventListener("click", function(){
div.textContent = "test" + div.id;
});
});
<div id="1">click me</div>
<div id="2">click me</div>
<div id="3">click me</div>
<div id="4">click me</div>
To set up just one handler and use event delegation:
- Assign a common handler to an ancestor of all the elements in question
- In the handler, act upon the specific element that triggered the event.
// Set up an event handler on the container element
document.querySelector(".parent").addEventListener("click", function(event){
// Act upon the target of the event (the element that triggered the
// event in the first place).
event.target.textContent = "test" + event.target.id;
});
<div class="parent">
<div id="1">click me</div>
<div id="2">click me</div>
<div id="3">click me</div>
<div id="4">click me</div>
</div>