Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript changes all array element 's HTML code

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?

like image 523
Mehmet Ali Avatar asked Jun 01 '26 20:06

Mehmet Ali


1 Answers

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"));
like image 136
guest271314 Avatar answered Jun 03 '26 09:06

guest271314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!