Molham Al Nasr
Molham Al Nasr

Reputation: 99

How to select all tag elements with JS

I have a question about how to select all tag elements in HTML page with JavaScript and apply an Event listener to them.

With jQuery we can do like this

$('td').on('click', function(){...});

But how can I do it with pure JavaScript? I have this code:

const el = document.getElementsByTagName('td');
el.addEventListener("click", function(){

    let cellColor = document.getElementById("colorPicker").value;
    this.backgroundColor = cellColor;
});

But this gives an error in console:

Uncaught TypeError: el.addEventListener is not a function at makeGrid (designs.js:34) at designs.js:42

Upvotes: 0

Views: 3463

Answers (3)

Mamun
Mamun

Reputation: 68933

getElementsByTagName() returns collection. You have to iterate over all the element to add the event:

Try with querySelectorAll() and forEach():

const el = document.querySelectorAll('td');
el.forEach(function(td){
  td.addEventListener("click", function(){
    let cellColor = document.getElementById("colorPicker").value;
    this.style.backgroundColor = cellColor;
  });
});

Please Note: querySelectorAll() is supported by all the modern browsers. Some older browsers does not support it.

Try the following with Array.prototype.forEach() if you want to work with older browsers:

const el = document.getElementsByTagName('td');
[].forEach.call(el, function(td){
  td.addEventListener("click", function(){
    let cellColor = document.getElementById("colorPicker").value;
    this.style.backgroundColor = cellColor;
  });
});
Cell Color: <input id="colorPicker" value="#FF5733"/>
<table>
  <tbody>
    <tr><td>11</td><td>12</td><td>13</td></tr>
    <tr><td>21</td><td>22</td><td>23</td></tr>
    <tr><td>31</td><td>32</td><td>33</td></tr>
  </tbody>
</table>

Upvotes: 4

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You need to loop through the el so that we can add listener to each element in el. Also, to organise your code properly you can separate out the listener function.

const el = document.getElementsByTagName('td');
for(var i=0; i<el.length; i++){
  el[i].addEventListener("click", clickFunction);
}
//listener function
function clickFunction(){
    let cellColor = document.getElementById("colorPicker").value;
    this.backgroundColor = cellColor;
}

Upvotes: 0

brk
brk

Reputation: 50291

el is a nodeList & it will not have any addEventListener method. Access each element in this list by first converting to array and use forEach. Then attach addEventListener to each of the element

const el = document.getElementsByTagName('td');
[].slice.call(el).forEach(function(item){
  item.addEventListener("click", function(){

    let cellColor = document.getElementById("colorPicker").value;
    this.backgroundColor = cellColor;
  });

})

Upvotes: 0

Related Questions