I am trying to learn more about the DOM and have been writing some traversal scripts. The algorithm I’ve come up with worked fine for part of what I was doing, but when I applied it to the whole body of the HTML document it got messed up. Here’s the HTML:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Lumen Tests</title>
<link rel='stylesheet' href='../../qunit/qunit.css' />
</head>
<body>
<div id='qunit'></div>
<div id='qunit-fixture'></div>
<div id='wrapper'>
<div id='header'></div>
<div id='content'>
<p id='para'>Lorem ipsum dolor sit amet.</p>
</div>
<div id='footer'></div>
</div>
<script src='../../qunit/qunit.js'></script>
<script src='../lib/traverse.js'></script>
<script src='../lib/lumen.js'></script>
<script src='features.js'></script>
</body>
</html>
And the JavaScript:
(function () {
'use strict';
function toArray(list) {
var array = [],
len = list.length,
i = 0;
while (i < len) {
array[i] = list[i];
i += 1;
}
return array;
}
function Traverse() {
var that = this;
this.allTags = function (node) {
var context = node || document.body,
children = [],
array = [],
len,
i = 0;
children = toArray(context.childNodes);
len = children.length;
while (i < len) {
if (children[i].nodeType === 1) {
array.push(children[i]);
array = array.concat(that.allTags(children[i]));
}
i += 1;
}
return array;
};
}
var foo = new Traverse();
window.Traverse = foo.allTags;
}());
alert(Traverse());
Now, this setup would work just fine when I passed document.getElementById('wrapper') to the traversal function, but when I leave it to use document.body it only gets two of the script elements. I tested this on Chrome 20.0.1132.34, Firefox 11.0, and IE 9 and they all had the same results. Through testing I did discover that the algorithm doesn’t pass anything up, the childNodes property on document.body gives a length of 10 and when I turn it to an array and alert it the output is text, div, text, div, text, div, text, script, text, script. Can any of you explain why childNodes is not picking up the last two script tags? Thank you!
By the time you call the traverse script, the other 2 scripts don’t exist yet. Call traverse on domready.