0

I am trying to concatenate a javascript variable into a paragraph tag in html. Don't know how or if this is possible. please help, thanks.

I've tried ${timePassed} and +'timePassed'

<body><p>Congratulations! You won! Would you like to restart?<div class="restart">
    <i class="fa fa-repeat"></i>
</div>Your time was + 'timePassed'</p></body>

It's not implying the variable timePassed into the paragraph tag.

Cœur
  • 37,241
  • 25
  • 195
  • 267
CodingChap
  • 1,088
  • 2
  • 10
  • 23

3 Answers3

0

You will need the tag to use javascript:

<p id="time">Your time was: </p>
<script>
    document.getElementById("time").innerHTML += timePassed;
</script>

I give the <p> an id so I can easily access it in JavaScript.

The document.getElementById function gets an element (an HTML tag) given its ID. So I tell it to get the element with the id "time", which is the <p> element.

Then I append onto the innerHTML (the text inside the <p> element) the JavaScript variable timePassed - that's the += operator.

Sabrina Jewson
  • 1,478
  • 1
  • 10
  • 17
0
<body>
  <p>
    Congratulations! You won! Would you like to restart?
    <span class="restart"><i class="fa fa-repeat"></i></span>
    Your time was <span id="time_passed_container"></span>
  </p>
</body>

And in your script

<script>
  var timePassed = 11;
  document.getElementById("time_passed_container").innerText = timePassed;
</script>
Amoliski
  • 160
  • 6
0

Create a <span id="timeDisplay"> at the position where you want to display the time. Then, use document.getElementById("timeDisplay").innerHTML = timePassed; to display the value of variable timePassed.

See this jsFiddle

www.admiraalit.nl
  • 5,768
  • 1
  • 17
  • 32