Noob question alert! I am working on a basic clock that updates every second, but its not updating because I get Uncaught Error: NOT_FOUND_ERR: DOM Exception 8. Basically i just need to change the removeChild() at the end of the function to something else, but I don’t know what to change it to. I want to remove the <p class="time"> that is being created.
function spitTime() {
var clock = new Date();
var hours = clock.getHours();
var minutes = clock.getMinutes();
var seconds = clock.getSeconds();
if (minutes <= 9) {
minutes = "0" + minutes;
}
if (seconds <= 9) {
seconds = "0" + seconds;
}
var displayTime = hours + ":" + minutes + ":" + seconds;
var newTimeElem = document.createElement("p");
newTimeElem.className = "time";
var timeText = document.createTextNode(displayTime);
newTimeElem.appendChild(timeText);
document.getElementById("timePlace").appendChild(newTimeElem);
document.getElementById("timePlace").removeChild();
}
relevant HTML:
<div class="clock">
<span id="timePlace"></span>
</div>
According to your question, you don’t want to remove a child, you want to change the text of an existing element.
For this, you can use
textContent:It is to be noted that this isn’t cross browser. IE8 and below work with
innerTextinstead. A quick hack to use is this way:However, it is a hack. It will work nicely for your case, but don’t rely on this.
If you really want cross browser compatibility, you’re using jQuery by the way (or any other library like this). jQuery way to change text:
It uses
nodeValue, the only real cross-browser way to deal with text. It has to do this recursively though, because it is only available ontextNodes. It is equivalent to usingdata(as @amnotiam does in the comments of your question).