Skip to content Skip to sidebar Skip to footer

Innerhtml Modifying Whole Array

I have got an unexpected behavior from my Javascript code. I'm creating a line of table with document.createElement('tr') and an array of cells with that code: cellule = new Array(

Solution 1:

Because 'filll' was used, the same td was copied, causing an issue. One way is to create an independent td.

ligne = document.createElement("tr");
var datas = ['Chat', 'Chien', 'Alligator'];
for(var i=0; i<datas.length; i++) {
    var td = document.createElement("td");
    td.innerHTML = datas[i];
    ligne.appendChild(td);
}

maTable.appendChild(ligne);

Solution 2:

Your issue is with:

cellule = new Array(3).fill(document.createElement("td"));

Here you are creating an array with 3 of the same td elements. So when you change the one at index 0, you are also changing the one at index 1 and 2 as you are referencing the same element in memory.

An easy way to fix this is to manually create an array using a for loop and pushing unique references of the element into your cellule array.

See example below:

var maTable = document.getElementById("myTable");
var ligne = document.createElement("tr");;

var cellule = [];
for(var i = 0; i < 3; i++) {
  cellule.push(document.createElement("td"));
}

cellule[0].textContent = "Chat"; // use textContent instead of innerHTML if only adding text
cellule[1].textContent = "Chien";
cellule[2].textContent = "Alligator";

ligne.appendChild(cellule[0]);
ligne.appendChild(cellule[1]);
ligne.appendChild(cellule[2]);
maTable.appendChild(ligne);
<tableid="myTable"border="1"></table>

Solution 3:

fill add the same element (with the same reference) into your array.

You can put your elements with another way, like

cellule = [];
for (let i = 3; i--;) {
  cellule.push(document.createElement("td"));
}

or

cellule = newArray(3);
for (let i = cellule.length; i--;) {
  cellule[i] = document.createElement("td");
}

Solution 4:

When fill gets passed an object, it will copy the reference and fill the array with references to that object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#Description

Here is one of the way you could achieve the same.

    cellule = newArray(3).fill("")
    cellule.forEach((el,index) => cellule[index] = document.createElement("td"))
    cellule[0].textContent = "Chat"; 
    cellule[1].textContent = "Chien";
    cellule[2].textContent = "Alligator";
    console.log(cellule[0].textContent);
    console.log(cellule[1].textContent);
    console.log(cellule[2].textContent);

Post a Comment for "Innerhtml Modifying Whole Array"