Colle
Colle

Reputation: 154

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?

Upvotes: 0

Views: 683

Answers (2)

Jacob Helton
Jacob Helton

Reputation: 173

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";
});

Upvotes: 1

sanketd617
sanketd617

Reputation: 809

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";
   }
}

Upvotes: 1

Related Questions