David
David

Reputation: 119

How would I insert a JavaScript variable into HTML?

I want to do something like this:

<span class="scoreboard">Your score is ${score}</span>

and then have javascript like this:

let score;
// do score stuff

Basically have dynamic HTML. I googled this but didn't find anything relevant. I have this right now

function draw() {
  // ignore this game.screen.innerHTML = "";
  // and this tilemap.map.forEach(elem => game.screen.innerHTML += `${elem}<br>`);
  game.scoreboard.innerHTML = `Score: ${player.collected}`;
}

this is mostly personal preference so I understand that its irrelevant

Upvotes: 1

Views: 209

Answers (2)

Youssouf Oumar
Youssouf Oumar

Reputation: 46261

You could do it this way:

let score;
// do score stuff
document.querySelector(".scoreboard").innertText = `Your score is ${score}`;

Upvotes: 0

Viktor
Viktor

Reputation: 167

Like so?

let score = 5;
document.querySelector('span.scoreboard').innerText = `Your score is ${score}`;

You need something more than HTML to create dynamic content.

Upvotes: 1

Related Questions