2

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?

1
  • There is only one element being created. Then you fill your array with the same object (element). Commented Feb 1, 2019 at 18:40

2 Answers 2

6

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"));
Sign up to request clarification or add additional context in comments.

Comments

3

Your array is bs_length elements long, but they are all actually the same. Like in many OOP languages, you need to understand the difference between a primitive / immutable value (e.g. 1, true, "hello") and objects (e.g. [1, 2, 3], {foo: "bar"}, or DOM elements). The latter are not trivially copied and if you do a fill with an element, you fill the array with references to the one element. @guest271314's answer provides an one-liner to fill with new elements. It is a shortcut to something like:

let bs_divs = new Array(bs_length);
for (let i = 0; i < bs_length; i++) {
  bs_divs[i] = document.createElement("div");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.