404
Appendix II
text-utils.js
Once you’ve got your asynchronous JavaScript taken care of, you’re ready to tackle some
DOM code. You learned about the Document Object Model in Chapter 4, but we used the
text-utils.js le in several earlier chapters... before you were the DOM guru that you’ve
since become. Here’s the code for text-utils.js, along with lots of notes on how it works.
function replaceText(el, text) {
if (el != null) {
clearText(el);
var newNode = document.createTextNode(text);
el.appendChild(newNode);
}
}
function clearText(el) {
if (el != null) {
if (el.childNodes) {
for (var i = 0; i < el.childNodes.length; i++) {
var childNode = el.childNodes[i];
el.removeChild(childNode);
}
}
}
}
function getText(el) {
var text = “”;
if (el != null) {
if (el.childNodes) {
for (var i = 0; i < el.childNodes.length; i++) {
var childNode = el.childNodes[i];
if (childNode.nodeValue != null) {
text = text + childNode.nodeValue;
}
}
}
}
return text;
}
changing a web page
replaceText() takes an element, and replaces all the
text in the element with the text you supply.
First, we use clearText() to get
rid of any existing children.
Next, we use the document object
to create a new text node, and then
append it to the element’s child nodes.
clearText() removes all the child nodes of
the element you pass to the function..
This loops through all the child
nodes, and removes each one. ...