Javascript – How to target first td of every row with pure JS

javascript

I tried to change the color of the first td element in each row to red.

HTML:

<table id="test">
<tr>
    <td>test1</td>
    <td>test2</td>
</tr>
<tr>
    <td>test3</td>
    <td>test4</td>
</tr>

</table>

I tried this JS:

var tr = document.getElementsByTagName('tr');

tr.firstChild.style.color = 'red';

No Jquery please.

Best Solution

Use rows and cells to access the rows and columns of the table. See below code,

var table = document.getElementById('test');
for (var i = 0; i < table.rows.length; i++) {
   var firstCol = table.rows[i].cells[0]; //first column
   firstCol.style.color = 'red'; // or anything you want to do with first col
}

DEMO: http://jsfiddle.net/QNEyx/