I want to create HTML objects using JS native script. I hae a function, that paints some text and I want to optimize it.
When I use it, it must write some text in HTML using loop to make several different iterations but instead I found out that new loop does not make a new object in HTML but remakes previous.
paintPrimary: (id, alias, country, date, content) => {
let primaryArray = ['Alias', 'Country', 'Date', 'Description'];
console.log(primaryArray);
const $primary = document.createElement('div');
$primary.className = 'teamHeaders';
for (let primaryCounter = 0; primaryCounter < primaryArray.length; primaryCounter ++) {
$primary.innerHTML = primaryArray[primaryCounter];
document.getElementById(id).appendChild($primary);
}
}
I tried to use constructors but had no success. Was thinking of making a new variable for every iteration everytime, but I dont know how to do such a thing and havent found any info
2
Answers
Create the element
div
inside the loop. In your case you are creating thediv
only once, so it is overwritingTry this:
When you call
paintPrimary
multiple times, it will create separate sets of div elements for each call, rather than overwriting the previous content.