I'm trying to make the onclick
event work for all rows of a table. But, it doesn't matter what row I click, the event only seems to fire for the last tr
. I made a simple example to illustrate the problem on JSFiddle.
HTML:
<table>
<tr>
<td>Test</td>
<td>Test2</td>
</tr>
<tr>
<td>Test</td>
<td>Test2</td>
</tr>
<tr>
<td>Test</td>
<td>Test2</td>
</tr>
<tr>
<td>Test</td>
<td>Test2</td>
</tr>
</table>
Javascript:
var table = document.getElementsByTagName( "table" )[0];
for( var contador = 0; contador < table.getElementsByTagName( "tr" ).length; contador++ ){
var line = table.getElementsByTagName( "tr" )[contador];
line.onclick = function() {
line.innerHTML = "Row clicked";
};
}