How do I change the border color of a & lt; td & gt; using JavaScript?

advertisements

I'm trying to change the colour of a <td> in my .html file. Here is what I have but for some reason it doesn't seem to be working.

My .html file:

<table>
    <tr id = "table_row">
        <td>Computers</td>
        <td>Price</td>
        <td>Location</td>
   </tr>
</table>

And now my .js file:

function changeBorderColor() {
    var table = document.getElementById("table_row").getElementsByTagName("td");
    table.style.borderColor = "red";
}

Why doesn't my <td> change colour when I activate the changeBorderColor() function? Thanks in advance for any tips and help!


The getElementsByTagName() method will return an array of elements matching the tag selector. So you would need to iterate througth it to change each element:

Simple example:

function changeBorderColor() {
    var table = document.getElementById("table_row").getElementsByTagName("td");
    for(var i=0; i<table.length; i++) {
        var td = table[i];
        td.style.borderColor = "red";
    }
}