I have a function that has to display a number(score of the player) in the DOM. But I can't see anything
victory() {
let score = document.getElementById("score")
score.innerHTML = 123
}
<div id="victory-text" class="overlay-text overlays">
Victory
<span id="score" class="overlay-text-small">Your score:</span>
<span class="overlay-text-small">
Click to restart
</span>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
I have called the victory()
function in another function. If instead of score.innerHTML = 123
if I hadscore.innerHTML = "Hello World"
it gets displayed like your score: Hello World
. So I think it is only the problem with numbers.
The number "123" is just a hardcoded value and later I will insert the number(the actual score) dynamically. But the hardcoded value is also not being displayed as well as the dynamic one. Can someone please help me with this? I am just getting started off with javascript
CodePudding user response:
You must parse the existing number and then add to it. innerHTML =
is not intended to do math.
Here is an example using parseInt.
function victory() {
let score = document.getElementById("score");
score.innerText = parseInt(score.innerText) 123;
}
victory();
CodePudding user response:
You forgot to declare victory as function.
function victory() {...}
instead victory() {...}
function victory() {
let score = document.getElementById("score");
score.innerHTML = 123;
}
victory();
<div id="victory-text" class="overlay-text overlays">
Victory
<span id="score" class="overlay-text-small">Your score:</span>
<span class="overlay-text-small">
Click to restart
</span>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Assigning element.innerHTML
is a red flag that something might not be quit right. Adding content to html should generaly happen through element.innerText
Another problem is that you apend the score to the existing html. That means that if you call the function a second time the previous score will still be shown.
function victory() {
let score = document.getElementById("score");
score.innerText = (123).toString();
}
victory()
<div id="victory-text" class="overlay-text overlays">
Victory
<span class="overlay-text-small">Your score: <span id="score"></span></span>
<span class="overlay-text-small">
Click to restart
</span>
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Now you can call the function multiple times without problems while avoiding element.innerHTML
.