Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  147] [ 4]  / answers: 1 / hits: 34461  / 11 Years ago, thu, october 3, 2013, 12:00:00

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?


More From » html

 Answers
30

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

[#75262] Wednesday, October 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alejandro

Total Points: 231
Total Questions: 102
Total Answers: 107

Location: Jordan
Member since Wed, Jun 17, 2020
4 Years ago
alejandro questions
Mon, Jul 18, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Thu, Sep 10, 20, 00:00, 4 Years ago
;