0

Why when I use .getElementById() (I used it as a test) works but querySelectorAll() doesn't work and throws "addEventListener is not a function?" Is it because I am selecting multiple buttons or is there a multiple addEventListeners syntax that exists?

const btn = document.querySelectorAll("marker");

btn.addEventListener("click", () => {
    console.log("works");
});
btn.addEventListener("click", () => {
    if (btn.style.backgroundColor === "green") {
        btn.style.backgroundColor = "red";
        btn.innerHTML = "-";
    } else {
        btn.style.backgroundColor = "green";
        btn.innerHTML = "+";
    }
});
<!DOCTYPE html>
<html>
    <head>
        <title>Marking</title>
    </head>
    <body>
        <script src="script.js" defer></script>
        <div id="main">
            <button id="marker" style="background-color: green">+</button>
            <button id="marker" style="background-color: green">+</button>
            <button id="marker" style="background-color: green">+</button>
            <button id="marker" style="background-color: green">+</button>
            <button id="marker" style="background-color: green">+</button>
            <button id="marker" style="background-color: green">+</button>
        </div>
    </body>
</html>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
imback0526
  • 164
  • 2
  • 9
  • `querySelectorAll` expects a CSS selector, so you need to pass `#marker` – m90 Apr 20 '21 at 08:49
  • Aside: you have multiple elements of id "marker" in your code. Ids should be unique for a document, so you probably want to use a classname instead. – m90 Apr 20 '21 at 08:50
  • 1. An id should be unique per page. It is bad practice to have multiple elements with the same id. 2. querySelectorAll returns an Array-like object. If you want to add an event listener to each elem you need to iterate over the return with forEach and assign the event listener per elem. Like this ```document.querySelectorAll((elems) => elem.addEventListener('event', fn))``` 3. You can use querySelectorAll for both ids and classes. classes are prefixed with a '.' and ids with a '#' – uke5tar Apr 20 '21 at 08:54
  • thx for the help – imback0526 Apr 20 '21 at 08:55

0 Answers0