0

I have: about, calculator, contact and I want to create one function for all of the elements, but during testing, it works only for the first element. Thanks for the help!

let tool = document.querySelector(".tool");

tool.onclick = function(event) {
  console.log(event.target.id);
};
<ul class="tools">
  <li class="tool" id="about"><i class="fas fa-question blue"></i> - about</li>
  <li class="tool" id="contact"><i class="fas fa-phone blue"></i> - contact</li>
  <li class="tool" id="calculator"><i class="fas fa-calculator blue"></i> - calculator</li>
</ul>
j08691
  • 204,283
  • 31
  • 260
  • 272
Horki
  • 39
  • 7

2 Answers2

1

You may use querySelectorAll for selecting all the elements with the provided class name and iterate over them and binding your click handler.

let tools = document.querySelectorAll(".tool");
for (var i = 0; i < tools.length; i++) {
  tools[i].onclick = function(event) {
    console.log(event.target.id);
  }
}
<ul class="tools">
  <li class="tool" id="about"><i class="fas fa-question blue"></i> - about</li>
  <li class="tool" id="contact"><i class="fas fa-phone blue"></i> - contact</li>
  <li class="tool" id="calculator"><i class="fas fa-calculator blue"></i> - calculator</li>
</ul>
user1987
  • 231
  • 1
  • 6
0

See MDN:

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors.

and

If you need a list of all elements matching the specified selectors, you should use querySelectorAll() instead.

But see also: What do querySelectorAll and getElementsBy* methods return?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335