Manipulating css

document.querySelectorAll(".change")[0].style.backgroundColor = z;
            document.querySelectorAll(".change")[1].style.backgroundColor = z;
            document.querySelectorAll(".change")[2].style.backgroundColor = z;

Any possible way so that upper statements can be reduce to a single line. I tried document.querySelectorAll(".change").style.backgroundColor = z; it didn’t work out.

With a loop? A for loop with i from 0 to 2.

const changeElementsArray = document.querySelectorAll(".change")
for (let i = 0; i <= 2; i++) {
changeElementsArray[i].style.backgroundColor = z;
}

or using the forEach function.

1 Like

Okay. That is one way. I thought there might be an inbuilt DOM manipulation function that would simultaneously update all the classes.

I don’t know of a built-in DOM function to do that in one line, but you could do something like that with D3.js.

d3.selectAll(’.change’).style(‘backgroundColor’, z);

Like @zdflower says, there is no bulit-in way, but you could always use jQuery:

$('.change').css("background-color", "red");

or a modified version of @zdflower’s original suggestion to have a one-liner.

[...document.querySelectorAll(".change")].map(elem => elem.style.backgroundColor = z);