0

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

1
  • querySelector returns the first element you need to use querySelectorAll Commented Jun 4, 2016 at 11:18

4 Answers 4

4

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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>

2 Comments

Thank you! This was the simplest solution.
@user2994590 This will alert if you click in the list outside the links.
2

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>

Comments

0

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");
   })
});

1 Comment

Just FYI, you need to convert the return value of querySelectorAll to an Array before you can call Array methods on it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.