Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to target first td of every row with pure JS?

Tags:

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.

like image 772
dzumla011 Avatar asked May 13 '13 19:05

dzumla011


3 Answers

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/

like image 93
Selvakumar Arumugam Avatar answered Oct 23 '22 07:10

Selvakumar Arumugam


Parsing with JS could be costly, if you are fine achieving the same with the CSS, then here you go.

#test tr td:nth-of-type(1) {
   color: red;
}

Or

#test tr td:first-child {
   color: red;
}
like image 8
Mr. Alien Avatar answered Oct 23 '22 08:10

Mr. Alien


As said in another reply, css is the natural way to accomplish this.

As you are stuck with js, you can use js to inject a stylesheet in your page:

var styleNode=document.createElement("style");
document.head.appendChild(styleNode);
var cssString="#test tr td:first-child {color: red;}";
if (styleNode.styleSheet) { // IE
  styleNode.styleSheet.cssText = cssString;
}
else {
  styleNode.appendChild(document.createTextNode(cssString));
}

The benefit of using a stylesheet is that you avoid race conditions (case when the table is built dynamically).

like image 2
Christophe Avatar answered Oct 23 '22 08:10

Christophe