Reputation: 25
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
Upvotes: 0
Views: 1416
Reputation: 8385
Use querySelectorAll in place of querySelector and which will return an array and loop it through in foreach and add event listener to all.
var links = document.querySelectorAll("a");
Array.from(links).forEach(function(e) {
e.addEventListener("click", function() {
alert("clicked");
})
});
Upvotes: 0
Reputation: 323
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>
Upvotes: 2
Reputation: 115272
Method querySelector()
only select single element, instead use querySelectorAll()
and bind click event handler using iterator.
// convert NodeList to Array and then iterate using forEach method
Array.from(document.querySelectorAll("a")).forEach(function(ele) {
ele.addEventListener("click", function() {
alert("Hello world");
})
});
<body>
<ul id="test">
<li><a href="#">First</a>
</li>
<li><a href="#">Second</a>
</li>
</ul>
</body>
Upvotes: 2
Reputation: 122135
You need to use querySelectorAll()
to select every a
and then use for
loop because it returns NodeList
var a = document.querySelectorAll("a");
for (var i = 0; i < a.length; i++) {
a[i].addEventListener("click", function() {
alert("Hello world");
});
}
<ul id="test">
<li><a href="#">First</a></li>
<li><a href="#">Second</a></li>
</ul>
Upvotes: 4