简体   繁体   中英

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?

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM