Reduce code size

Reduce code size
0

Hi, I have this code that is activated by pressing a key

//Example 1
document.getElementById("one", "two", "three", "four", "five").style.backgroundColor = "#2fcc71";

but it doesn’t work and I have to write it this way

//Example 2
document.getElementById("one").style.backgroundColor = "#2fcc71";
document.getElementById("two").style.backgroundColor = "#2fcc71";
document.getElementById("trhee").style.backgroundColor = "#2fcc71";
document.getElementById("four").style.backgroundColor = "#2fcc71";
document.getElementById("five").style.backgroundColor = "#2fcc71";

How can I do to reduce the code in the second example?

getElementById only takes one argument.

To avoid repetition, you could write a loop.

I will look for how to write it. Thanks for your answer

I would try something like this:

const ids = ["one", "two", "three", "four", "five"];
const backgroundColor = "#2fcc71"

// Loop over the ids array using the Array.forEach method
ids.forEach(id=> {
    // For each id in the ids array, the background color to the value assigned to the backgroundColor constant.
    document.getElementById(id).style.backgroundColor = backgroundColor;
});

Documentation:

Document.getElementById()

const

Array

Array.forEach