user2994590 user2994590 - 5 months ago 14
HTML Question

addEventListener not working for multiple links

I am new to javascript, and am having trouble making a click event handler working on multiple links. My code is given below:

<body>
<ul id="test">
<li><a href="#">First</a></li>
<li><a href="#">Second</a></li>
</ul>
</body>


and the JS code:

document.querySelector("a").addEventListener("click", function() {
alert("Hello world");
});


The event works fine for the "First" link, but not for the second. Any ideas where I am going wrong. FIDDLE

Answer

Use this for the JS:

var links = document.getElementById("test");

links.addEventListener("click", function() {
    alert("Hello world");
});
<body>
<ul id="test">
<li><a href="#">First</a></li>
<li><a href="#">Second</a></li>
</ul>
</body>

Comments