I'm trying to create "div" elements and trying to change their inner HTML with Javascript but it doesn't change the specific element of an array instead it changes all element's HTML code.
let bs_length = 2;
const bs_divs = new Array(bs_length).fill(document.createElement("div"));
bs_divs[0].innerHTML = "Hi";
console.log(bs_divs[0].innerHTML); // Hi
console.log(bs_divs[1].innerHTML); // Hi
How can I change this code so that it only changes first element's HTML?
When fill gets passed an object, it will copy the reference and fill the array with references to that object.
Use Array.from()
Array.from({length:bs_length}, () => document.createElement("div"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With