Good day. Need help. There is a table, I want to make every element clickable. This is how it works:

var variable = document.getElementById('test'); 

But clickable only the first element is obtained naturally.

 variable.addEventListener("click", showNumber); 

I try so that all:

 var variable = document.getElementsByTagName('td'); var variable = document.querySelectorAll('.class'); variable.addEventListener("click", showNumber); 

Does not work.

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

querySelectorAll and getElementsByTagName return collections, therefore, to assign a handler, you need to go through the entire collection and assign it to each element, for example:

 var variables = document.querySelectorAll('.class'); [].forEach.call(variables, function(variable){ variable.addEventListener("click", showNumber); }); 
  • Why spend money on creating an empty array and searching in its prototype method? Array.prototype simpler. - user207618
  • @Other, write longer, as well as tests show that there is not much difference. Is there any reason to say that Array.prototype better than easier ? Moreover, it is not entirely clear what this word means in this case - Grundy
  • Some foamed at the mouth argued that it is cheaper to take directly from the prototype than to create and search. Too lazy to check, so I just suggested. - user207618
  • @Other, it is worth noting that literals are not entirely ordinary objects - Grundy
  • Yes, but when interpreting, they are still passed through the designer’s meat grinder. - user207618

The events of the click “bubbles” go up: from <td> to <tr> and <table> . Maybe just catch the click event at <table> - and determine the original initiator of the click?

 var table = document.getElementById('e-table'), out = document.getElementById('out'); table.addEventListener('click', function(e){ if( e.target.tagName !== 'TD') return; // ждём клика по <td> out.innerHTML = e.target.innerHTML; }); 
 body{font-family:Helvetica,Arial,sans-serif;} td{border:1px solid #CCC; cursor:pointer; width:15px;height:15px; text-align:center} #out{padding:5px;width:60px;height:40px;background-color:#CCC;text-align:center} 
 <table id="e-table"> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>A</td> <td>B</td> <td>C</td> </tr> <tr> <td>.</td> <td>..</td> <td>...</td> </tr> </table> <div id="out"></div>