Using a DOM approach instead of innerHTML

We have already seen how to modify the text (actually, an HTML fragment) included in an element accessing its innerHTML property.

The issue is that innerHTML is not a standard property, so we shouldn't actually rely on it. Expecially if we consider that we cand do the same considering the element as a node in the document, accordingly to the DOM (Document Object Model), and accessing its included text as its child.

To see this approach in action let's build an HTML page containing an image and its caption. We want our JavaScript being able to initialize and change the actual picture and text, so we put just the structure in the HTML code, and leave to the script the fun of assigning the content:

<body>
<div style="margin-top: 100px; text-align: center;">
<p><img id="sceneImg" alt="" src=""></p>
<div id="sceneTxt"></div>
</div>
</body>

We initialize the HTML from the script assiging an anonymous callback function to window.onload. Here we see what we were used to do, using innerHTML:

window.onload = function(evt) {
document.getElementById("sceneImg").alt = "The first scene image";
document.getElementById("sceneImg").src = "scene1.png";
document.getElementById("sceneTxt").innerHTML = "This is the first scene";
}

The same result of calling the third line could be achieved removing all the children from the node "sceneTxt" and assigning to it a new text node containing the requested string. To keep the code simpler, we could use a short function like this:

function setTextElement(elemId, newTest) {
var node = document.getElementById(elemId);
while(node.firstChild)
node.removeChild(node.firstChild);
node.appendChild(document.createTextNode("This is the first scene"))
}

That would be called from the anonymous function in this way:
setTextElement("sceneTxt", "This is the first scene");

More details on DOM in chapter eight of Head First JavaScript.

No comments:

Post a Comment