Oscar Dulzaides Oscar Dulzaides - 2 months ago 7
HTML Question

appedChild() overwriting divs

I have an array with a nested array that will add divs to the DOM in a loop from the items in the array. When it goes into the nested loop it keeps overwriting the previous div with the last item in the nested array. I cant't figure out why this is happening.

Here is my code:

let beans = ["1", "2", "3", ["4", "5", "6"]];

//Loop over the beans array
for (var i = 0; i < beans.length; i++) {

// create div elements


// check to see if it is string
if (typeof beans[i] === 'string') {
let divs = document.createElement('div');
divs.textContent = beans[i];
document.body.appendChild(divs);

// console.log(beans[i]);
} else {
let divs = document.createElement('div');
divs.textContent = "These are the array items:";
document.body.appendChild(divs);
for (var j = 0; j < beans[i].length; j++) {

divs.textContent = beans[i][j];
document.body.appendChild(divs);
console.log(i + " " + j + " " + beans[i][j]);
}
}
}


what i end up getting is 4 divs:
1
2
3
6

so the divs in the nested array overwrite themselves.

I am relatively new to JS and would appreciate any help on this.

Answer

Your else only creates one new element - notice that it calls document.createElement('div') exactly once, before the loop? You then overwrite that div's content and call document.body.appendChild(divs), but .appendChild() doesn't create additional copies, it moves existing elements.

You need to add another call to document.createElement('div') inside the for loop in the else.

let beans = ["1", "2", "3", ["4", "5", "6"]];

//Loop over the beans array
for (var i = 0; i < beans.length; i++) {
    // create div elements
    // check to see if it is string 
    if (typeof beans[i] === 'string') {
        let divs = document.createElement('div');
        divs.textContent = beans[i];
        document.body.appendChild(divs);
    } else {
        let divs = document.createElement('div');
        divs.textContent = "These are the array items:";
        document.body.appendChild(divs);
        for (var j = 0; j < beans[i].length; j++) {
            divs = document.createElement('div');        // <--- ADD THIS
            divs.textContent = beans[i][j];
            document.body.appendChild(divs);
            console.log(i + " " + j + " " + beans[i][j]);
        }
    }
}