简体   繁体   中英

Change style of table cells on click

I want to change the color of specific table cells when clicking a button.

<button onclick="highlight()">Toggle highlighting</button>

And JS:

function highlight() {
    var x = document.getElementsByClassName('best');
    for (var i = 0; i < x.length; i++) {
        x.get(i).style.color = "green";
    }
}

I added the table cells I want to change to the class "best", but when clicking the button, nothing changes. I first tried to assign them all to a single ID and use document.getElementById('best').style.color = "green"; , but this only changed the first element that had the id "best" and not all. How should highlight() look like?

You don't need to use x.get(i) there. Just access the element using x[i]

See the following code:

function highlight() {
   var x = document.getElementsByClassName('best');
   for (var i = 0; i < x.length; i++) {
     x[i].style.color = "green";
   }
}

First off, I'd recommend using Javascript's built in forEach() function when working with a nodeList like this as there is less chance of an off by one error:

bestElements.forEach(best => {
  best.style.color = "green";
});

Second, I believe you may be looking for the background-color attribute, not the color attribute if you are trying to change the color of the entire cell.

bestElements.forEach(best => {
  best.style.backgroundColor = "green";
});

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