To rewrite text in HTML
There myEmployees
are 5 names in my array , but it only outputs 3 of them when I run the code. I believe this is because the loop for
in the script is overwriting the previous line that it wrote in the HTML document. How can I fix this?
Annual bulletin board announcements!
Congratulations to Taylor, you have been here for 9 years and you will meet a magic number! You get 2 extra weeks from PTO!
Derek, thank you for your service over the past 8 years. I look forward to working with you for many years!
Tyler doesn't work here anymore.
The above shows that two other statements should appear on my screen when I run the code. Any suggestions would be appreciated!
<body>
<h1>Yearly Buttetin Board Announcements!</h1>
<h2 id='win'></h2>
<h3 id='here'></h3>
<h4 id='notHere'></h4>
<script src='app.js'></script>
</body>
TypeScript
for( i = 0; i < myEmployees.length; i++ ) {
const employee = myEmployees[i];
let magicNumber = employee.extraVacay;
let stillEmployed = employee.stillEmployed;
let timeInJob = employee.timeInJob;
let name = employee.name;
if( magicNumber > 30 && timeInJob > 5 && stillEmployed == true ) {
document.getElementById('win').innerHTML = (`Congratulations to ${name}, you have been here for ${timeInJob} years and you meet the magic number! You get 2 extra weeks of PTO!`);
}
else if (stillEmployed == true) {
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!`);
}
else {
document.getElementById('notHere').innerHTML = (`${name}, no longer works here.`)
}
};
source to share
The below statement overrides 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 need to add the previous value to the new text. The updated code should look something like this:
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!`);
source to share
Use insertAdjacentHTML
document.getElementById('here').insertAdjacentHTML('beforeend', 'your html')
It may have better performance than using innerHTML, especially when used beforeend
.
source to share