Sanderr Sanderr - 10 months ago 44
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 (

) a onClick event.

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

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


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:



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')