'Don't write innerHTML in same span everytime function is called
var villains = 500;
var hero = 500;
function beth() {
he();
}
function betv() {
}
function he() {
setTimeout(function() {
var x = Math.floor((Math.random() * 300) + 1);
var vhp = villains - x;
villains=vhp;
if (villains< 0 ) {
document.getElementById("res1").innerHTML = "Heroes have won";
document.getElementById("res2").innerHTML = "<br/>Villains have lost to heroes";
} else {
document.getElementById("res1").innerHTML += "<br/>Heroes have dealt " + x
+ " damage on villains.<br/>Villains have " + vhp
+ " hp left.";
vok();
}
},3000);
}
function vok() {
setTimeout(function() {
var y = Math.floor((Math.random() * 300) + 1);
var hhp = hero - y;
hero=hhp;
if (hero<0) {
document.getElementById("res2").innerHTML = "<br/>Heroes have " + 0 +" Hp left";
document.getElementById("res1").innerHTML = "<br/>Heroes have lost to villains";
} else {
document.getElementById("res2").innerHTML += "<br/>Villains have dealt "
+ y + " damage on Heroes.<br/>Heroes have " + hhp
+ " hp left.";
he();
}
},3000);
}
Abve Code is for js its printing text1 newtext2 newtext3 while I want text1 text2 newtext1 newtext2 newnewtext1 newnewtext2. Any tips or suggestions how can we do it? Would appreciate any answers or feedbacks. I also want after the finish the condition for if is met to reset everything
Solution 1:[1]
You're replacing the span every time by assigning new value to it (=). Instead you should append the value using +=, wherever you want your span value to be added.
document.getElementById("res1").innerHTML += "Heroes have dealt " + x + " damage on villains.";
Solution 2:[2]
Right now, you are using the = operator, which means to replace/overwrite the value currently set to the HTML element (in this case, the span element).
To fix this issue, you need to replace = with +=. The += operator appends to the end of the string, instead of overwriting the text.
So, you would change your code to be the following. The code below updates the span tag to have some extra text at the end, instead of overwriting it all.
const welcome = document.querySelector("#welcome");
welcome.innerHTML += "I'm on Stack Overflow!";
<!-- Extra whitespace is intentional -->
<span id="welcome">Hello! </span>
However, if you want to add some text to the beginning of the text, you can just use the code below.
const intro = document.querySelector("#intro");
// The whitespace is intentional
intro.innerHTML = "Welcome to Stack Overflow! " + intro.innerHTML
<span id="intro">First check the Help page.</span>
In conclusion, there are two ways to add to HTML.
- Use the
+=operator. - Use the
+operator (with extra code).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Madhan S |
| Solution 2 | Arnav Thorat |
