Skip to content
Advertisement

How do you add an eventListener to a htmlCollection that will change the display of another element?

Aim : to click box(x) and it opens pop-up(x);

This is my first javascript project, i’ve done loads of research but i’m still struggling. The reason I’m using a getElementByClassList is because it returns an array. I would then take the array and get the corresponding pop-up box and change its display settings in css.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="box1 boxes"></div>
    <div>
        <div class="box2 boxes"></div>
        <div class="box3 boxes"></div>
    </div>
    <div class="popup1"></div>
    <div class="popup2"></div>
    <div class="popup3"></div>
    
    <script>
        const boxes = document.getElementsByClassName('boxes');
        // i would like to add an eventlistener for each object in the array
        //
    </script>
</body>
</html>

Advertisement

Answer

document.addEventListener("DOMContentLoaded", () => { // wait till all the DOM is Loaded, since querying objects at this point they are not there yet.
  const boxes = document.querySelectorAll(".boxes"); // or use getElementsBy...
  
  boxes.forEach(box => { // we are adding a click event listener to each box
    box.addEventListener('click', (e) => {
      const boxNumber = e.target.className.match(/box(d)/)[1]; // through a regex we get the box number of the className
      const popup = document.querySelector(`.popup${boxNumber}`);
      
      console.log(popup)
      // do whatever you want with the popup, add a className or whatever to open it :)
    });
  });
});
.boxes {
  height: 20px;
  width: 50px;
  background: red;
  margin: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="box1 boxes"></div>
    <div>
        <div class="box2 boxes"></div>
        <div class="box3 boxes"></div>
    </div>
    <div class="popup1"></div>
    <div class="popup2"></div>
    <div class="popup3"></div>
    
    <script>
        const boxes = document.getElementsByClassName('boxes');
        // i would like to add an eventlistener for each object in the array
        //
    </script>
</body>
</html>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement