Sanderr Sanderr - 4 months ago 9
Javascript Question

Javascript onClick event in all cells

I'm learning JavaScript and I've not that much experience.
But I'm making a HTML table and I want to add in every table cell (

<td>
) a onClick event.

<table id="1">
<tr>
<td onClick="tes()">1</td><td onClick="tes()">2</td>
</tr>
<tr>
<td onClick="tes()">3</td><td onClick="tes()">4</td>
</tr>
</table>


Is there another way to do this event in every cell?

Answer

There are two ways:

var cells = table.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
   cells[i].onclick = function(){tes();};
}

and the other way using jQuery:

$('td').click(function(){tes();});

upd:

To get exactly what is needed, firstly the table must be selected, so, for the first option:

var table = document.getElementById('1');
var cells = table.getElementsByTagName("td"); 
...

and for the second, the jQ selector should be like this:

$('#1 td')