When an event is fired on an element that has parent elements (e.g. the
div
in our case), modern browsers run two different phases — the capturing phase and the bubbling phase. In modern browsers, by default, all event handlers are registered in the bubbling phase, this is what happen:
-
The browser checks to see if the element that was actually clicked on has an
onclick
event handler registered on it in the bubbling phase, and runs it if so.
-
Then it moves on to the next immediate ancestor element and does the same thing, then the next one, and so on until it reaches the
html
element.
References
MDN Docs