In pure javascript,
Using elemento.getElementsByTagName(tag)
to get the list of the tags in this case are th and td
This returns an array of all the tags in the document, then to add it to all, but in these with a for cycle and I add the color with the method setAttribute(atributo,valor)
If you want NO, apply to the entire document, but only a div where those tags are found, because instead of doing document..getElementsByTagName(tag)
, you replace the 'document'
for your element, for example:
var div1 = document.getElementById("miDiv");
var titulos = div1.getElementsByTagName("TH");
var titulos2 = div1.getElementsByTagName("TD");
var t1 = titulos.length,t2=titulos2.length;
for(var i=0;i<t1;i++) {
titulos[i].setAttribute('style','color: red');
}
for(var i=0;i<t2;i++) {
titulos2[i].setAttribute('style','color: green');
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="miDiv">
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</div>
<div id="miDiv2">
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</div>
And in regards to your code here is:
var titulos = document.getElementsByTagName("TH");
var titulos2 = document.getElementsByTagName("TD");
var t1 = titulos.length,t2=titulos2.length;
for(var i=0;i<t1;i++) {
titulos[i].setAttribute('style','color: red');
}
for(var i=0;i<t2;i++) {
titulos2[i].setAttribute('style','color: green');
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
EYE: It's a well-known fact that it improves performance by saving the .length to an external variable