ILIAS ILIAS - 1 year ago 67
Javascript Question

Single event listener for multiple children elements

Consider the following HTML code:

<div id="left-box"></div>
<div id="middle-box"></div>
<div id="right-box"></div>

I want to change the color of
every time one of the above boxes is clicked. I am not presenting the CSSs. Is it possible instead of using 3 event listeners for click events upon the 3 boxes just to use only one? I've heard about fragments. Any idea?

Answer Source

You can use a single listener on the <section> which contains the three <div> elements, and then check for to see if one of those is clicked. So your code will only run if you click one of the three boxes, and not the parent <section> element.

Here's an example. I added an ID, class and some CSSs just for clarity.

var section = document.getElementById("container");

container.addEventListener("click", function(e) {
    if ( == "box") {
        // You clicked on a box =;

document.getElementById("left-box").style.backgroundColor = "red";
document.getElementById("middle-box").style.backgroundColor = "green";
document.getElementById("right-box").style.backgroundColor = "blue";
#container {
    background-color: yellow;
    display: inline-block;
    padding: 10px;

#container > div {
    width: 50px;
    height: 50px;
    margin: 5px;
    border: 1px solid yellow;
    display: inline-block;
<section id="container">
    <div class="box" id="left-box"></div>
    <div class="box" id="middle-box"></div>
    <div class="box" id="right-box"></div>