-2

unable to select second button using queryselectorall(). giving me an error "Uncaught TypeError: btn.addEventListener is not a function"

//HTML//

<!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>
    <button class="btn">A</button>
    <button class="btn">B</button>
</body>
<script src="app.js"></script>
</html>

//Javascript//

const btn = document.querySelectorAll(".btn");
btn.addEventListener('click' ,myfunction);

function myfunction(){
    console.log('hello');
}

1 Answers1

0

Actually The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Please try the below code,

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

btn.forEach(btn => {
     btn.addEventListener('click', () => {
        console.log('hello');
     })
     }
     );
<!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>
    <button class="btn">A</button>
    <button class="btn">B</button>
</body>
<script src="app.js"></script>
</html>
Santa
  • 367
  • 2
  • 8