The problem is when I clicked on DIV3, the color must be change to red but right now when all the div clicked then it shows me the red color instead of one by one, why is it not working?
You attached the event to “div”, not specific IDs. So every single div has a click listener attached.
When you click the innermost div, the event fires. But the event then bubbles up to the next parent and then the next parent all the way up.
So why do events bubble? Because other code might want to do other things too, and every div is going to want their chance at responding to the event. And there may be other scripts listening and many listeners attached to the same elements, etc etc. How do you know the user only specifically wanted to click the inner div? Maybe they were really clicking on the next parent but the inner one was in the way? It’s hard to tell, so the event bubbles up so each parent div can have a chance to decide if that click was meant for them.
If you as the programmer are absolutely SURE that when a div is clicked, that is the ONLY div anywhere up the chain which needs to respond to the event, then you can cancel the bubbling. But this is a dangerous assumption. There may be times where you have a UI with many elements inside a container, but you wan to attach general events to everything, like a right-click, but have the container respond to those events rather than each individual micro-element.
For example if you have a UI where a user can click on things and then some text appears in a status bar, you could attach a click handler to everything but let the parent container actually handle all those bubbled up events.
Just keep reading about event bubbling and how to properly stop it when you want to!
As @zack1 said, that’s because the event bubbles up the DOM tree. The usual approach would be to just stop the event propagation:
var divElement = document.getElementsByTagName('div');
var clickHandler = function (event) {
event.stopPropagation()
this.style.borderColor = 'red'
}
for (var i = 0; i < divElement.length; i++) {
divElement[i].addEventListener('click', clickHandler)
}
If you want to have the event keep bubbling, you could check if the target element is the same as the one that had the listener attached, like
var clickHandler = function (event) {
if (event.target === this) {
this.style.borderColor = 'red'
}
}