Hi im new to JavaScipt and testing my code. I want to add event listener to all buttons and make later on function that will perform different operation based on which button was clicked. So first im trying to test if i can add event listener to all of them via loop which i never tried before and then see if they react to click.But neither console.log nor alert output anything. What am i doing wrong?
Here is code:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
<link href="styles.css" rel="stylesheet">
<title>Trivia!</title>
<script>
var a=document.getElementsByTagName("button");
for(var i = 0; i < a.length; i++) {
a[i].addEventListener('click', function(){
console.log(a[i]);
});
}
</script>
</head>
<body style="background-color:blue">
<div class="header">
<h1>Trivia!</h1>
</div>
<div class="container">
<div class="section">
<h2>Part 1: Multiple Choice </h2>
<hr>
<h3>What song was played that day?</h3>
<div >
<button>A</button>
<button>B</button>
<button>C</button>
</div>
</div>
<div class="section">
<h2>Part 2: Free Response</h2>
<hr>
<>
</div>
</div>
</body>
</html>
`.
– T.J. Crowder Nov 16 '22 at 12:07