Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add an event listener to all items in array

so this is noobie .. but i am trying to complete a challenge with more due diligence than just downloading the answer,

my current html code is:

<!DOCTYPE html>
<html lang="en" dir="ltr">

    <head>
      <meta charset="utf-8">
      <title>Drum Kit</title>
      <link rel="stylesheet" href="styles.css">
      <link href="https://fonts.googleapis.com/css?family=Arvo" rel="stylesheet">
    </head>
    
    <body>
    
      <h1 id="title">Drum 🥁 Kit</h1>
      <div class="set">
        <button class="w drum">w</button>
        <button class="a drum">a</button>
        <button class="s drum">s</button>
        <button class="d drum">d</button>
        <button class="j drum">j</button>
        <button class="k drum">k</button>
        <button class="l drum">l</button>
      </div>
    
    
      <footer>
        Made with ❤️ in London.
      </footer>
      <script src="index.js" charset="utf-8"></script>
    </body>

my javascript codes :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   document.querySelector("button").addEventListener("click", handleClick);
    function handleClick() {
        alert("I got clicked!");
    }
    
    
    document.querySelectorAll(".drum")[1, 2, 3, 4, 5, 6].addEventListener("click", handleClick);

essentially, the current code is running the event listener
for the first and last item of the array only, trying to add it to all 6 but am stuck

thanks to all

>Solution :

document.querySelectorAll(".drum").forEach(el => el.addEventListener("click", handleClick));

You need a forEach to run some code on all elements.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading