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.
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.
<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>
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.