hiccup
hiccup

Reputation: 29

How to colour nth <td> element of a HTML table using JavaScript?

I tried using:

td:nth-of-type(5).style.backgroundColor("blue");

to colour 5th <td> element using JavaScript but I received:

Uncaught ReferenceError: nth is not defined at :1:4

What is the correct code to do it?

Upvotes: 0

Views: 501

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50684

You could use a CSS variable and change it's value in JS like so (please look at browser support for CSS variables):

document.documentElement.style.setProperty('--bg-color', "blue");
:root {
  --bg-color: initial; 
}

td:nth-of-type(5) {
  background: var(--bg-color);
}
<table border=1>
  <tr>
    <td>a.1</td>
    <td>a.2</td>
    <td>a.3</td>
    <td>a.4</td>
    <td>a.5</td>
    <td>a.6</td>
  </tr>

  <tr>
    <td>b.1</td>
    <td>b.2</td>
    <td>b.3</td>
    <td>b.4</td>
    <td>b.5</td>
    <td>b.6</td>
  </tr>
</table>

Alternatively, for something a little more browser compatible, you could use querySelectorAll() with .forEach() to loop through all selected elements using your selector:

document.querySelectorAll("td:nth-of-type(5)").forEach(td => {
  td.style.backgroundColor = "blue";
});
<table border=1>
  <tr>
    <td>a.1</td>
    <td>a.2</td>
    <td>a.3</td>
    <td>a.4</td>
    <td>a.5</td>
    <td>a.6</td>
  </tr>

  <tr>
    <td>b.1</td>
    <td>b.2</td>
    <td>b.3</td>
    <td>b.4</td>
    <td>b.5</td>
    <td>b.6</td>
  </tr>
</table>

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You can't use css like that in javascript. You'll need to use selector and assign the value like:

document.querySelector('td:nth-of-type(5)').style.backgroundColor = 'blue';

Look at the documentation for querySelector and querySelectorAll for more help.

Upvotes: 2

Related Questions