Skip to content Skip to sidebar Skip to footer

For Loop Overwriting Text In HTML

My array called myEmployees has 5 names in it, yet when I run the code it only prints out 3 of them. I believe this is happening because the for loop in the script is overwriting t

Solution 1:

You are correct-- innerHTML is overwriting the previous value-- use += instead:

document.getElementById('here').innerHTML += (`${name}, thank you for your service over the past ${timeInJob} years. I look forward to many more years working with you!`);

Solution 2:

You are indeed overwriting what you inserted in earlier. Instead of using a series of header tags, I would use an <ol> tag for 'win,' 'here,' and 'notHere', and append elements from the array when they meet the necessary conditions.


Solution 3:

The below statement is overriding the existing HTML.

 document.getElementById('here').innerHTML = (`${name}, thank you for your service over the past ${timeInJob} years. I look forward to many more years working with you!`);

You have to append the previous value to the new text. Updated code should look something like below

var prevText =  document.getElementById('here').innerHTML;
document.getElementById('here').innerHTML = prevText + (`${name}, thank you for your service over the past ${timeInJob} years. I look forward to many more years working with you!`);

Solution 4:

Use insertAdjacentHTML

document.getElementById('here').insertAdjacentHTML('beforeend', 'your html')

It can have better performance than using innerHTML, especially when using beforeend.


Post a Comment for "For Loop Overwriting Text In HTML"