Reputation: 71
Hi how do i display the javascript results in a div. the code is :
<script type='text/javascript'>
COUNTER_START = 40
function tick () {
if (document.getElementById ('counter').firstChild.data > 0) {
document.getElementById ('counter').firstChild.data = document.getElementById ('counter').firstChild.data - 1
setTimeout ('tick()', 1000)
} else {
document.getElementById ('counter').firstChild.data = 'done'
}
}
if (document.getElementById) onload = function () {
var t = document.createTextNode (COUNTER_START)
var p = document.createElement ('P')
p.appendChild (t)
p.setAttribute ('id', 'counter')
var body = document.getElementsByTagName ('BODY')[0]
var firstChild = body.getElementsByTagName ('*')[0]
body.insertBefore (p, firstChild)
tick()
}
</script>
i want it to display the coundown counter in this div
<div id="counter"></div>
Thank you :D
Upvotes: 0
Views: 1014
Reputation: 1075765
You can use innerHTML
for that:
document.getElementById("counter").innerHTML = /* ... HTML string here ... */;
You can shorten that script a fair bit: Live Example | Source
(function() {
var elm = document.getElementById('counter');
var counter = 40;
tick();
function tick() {
elm.innerHTML = String(counter);
--counter;
if (counter >= 0) {
setTimeout(tick, 1000); // <=== Note, a function ref, not a string
}
else {
elm = undefined; // Release it as we don't need it anymore
}
}
})();
I wasn't sure what the stuff with the paragraph element was, so I didn't include that. If it was meant to add the counter
element at the beginning of the body
(as a p
, not a div
), then just change
var elm = document.getElementById('counter');
to
var elm = document.createElement('p');
document.body.insertBefore(elm, document.body.firstChild);
Doesn't even need the id
. Live Example | Source
Upvotes: 3
Reputation: 2537
To change contents of div, use
document.getElementById("counter").innerHTML="something";
Upvotes: 0