CIT 597 Doing without innerHTML
Fall 2008, David Matuszek
The problems with innerHTML are
Here's what I'm doing in the JavaScript assignment. My XHTML looks like this:
<form action="">
Level: <span id="level">0</span><br />
Clicks: <span id="clicks">0</span><br />
<input type="button" value=" Start a New Game " onclick="prepareLevel(1);">
</form>
I call a function to change the contents of level and clicks.
My calls look like this:
setText("level", difficulty);
setText("clicks", clickCount);
Here's what that setText function used to look like:
function setText(id, n) {
var element = document.getElementById(id);
element.innerHTML = "" + n;
}
Here's what it looks like now:
function setText(id, n) {
var element = document.getElementById(id);
node = document.createTextNode("" + n);
element.removeChild(element.firstChild);
element.appendChild(node);
}
The article Alternatives to innerHTML provided the clues I needed to figure this out.