So, I'm just learning JS and trying to write a basic game using HTML/JS. I can't figure out how to update the score text.
I have a variable, "score", and a paragraph tag with the class "scoretext". I made a button, and I want to have it add 1 to the score when it is pressed. I have an onclick that says "score += 1" but I am unsure to to get the scoretext to update with the new score when the button is pressed.
Code:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: black;
color: white;
}
</style>
</head>
<body>
<p id="scoretext"></p>
<script>
var score = 0;
document.getElementById("scoretext").innerHTML = score;
</script>
<button onclick="score += 1;">Click</button>
</body>
</html>
You could just create a button that increases a score variable and then set the element to that score value.
<html>
<body>
<h1 class="scoretext">Score: 0</h1>
<button onclick="change()">Click Me!</button>
<script defer>
score = 0
function change(){
score++;
document.getElementsByClassName('scoretext')[0].innerText = "Score: " + score;
}
</script>
</body>
</html>