Skip to content

Instantly share code, notes, and snippets.

@Melipone
Created February 20, 2011 04:06
Show Gist options
  • Save Melipone/835682 to your computer and use it in GitHub Desktop.
Save Melipone/835682 to your computer and use it in GitHub Desktop.
Week 4 homework #2 on the Theory of the DOM
<script type="text/javascript">
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
function countTextNodes() {
var sum = 0;
function count (node) {
if (node.nodeType == 3) // TEXT_NODE
sum++;
}
var root = document.documentElement;
walkTheDOM(root, count);
var foo = document.getElementById("foo");
var newElement = document.createTextNode ("There are " + sum + " text nodes");
foo.appendChild(newElement);
}
</script>
<p id="foo">
<button type="button" onclick="countTextNodes()">Count Text Nodes</button>
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment