JavaScript DOM Traversal
I actually use the same code for java too (ok slightly modified). Traversing large DOM trees recursive is always a big memory issue... and in IE its a really pain, because memory usage=big decrease in performance (in Gecko/Opera?/etc. it doesnt seem to be such a big issue).
So here is the code that traverses a dom (sub)tree and does something on every node...
This example gets the content of all text nodes and returns the combined string, minus any whitespace (in corinis this is used to sort tables)
/** * go through every child node of root * (c) Niko Berger (license free or GPL or LPGL or BSD) */ function traverseDom (root) { var s = ''; var c = root, n = null; var it = 0; do { n = c.firstChild; if (n == null) { // visit c if (c.nodeType == 3) s += c.nodeValue.replace(/\s/, ""); // done visit c n = c.nextSibling; } if (n == null) { var tmp = c; do { n = tmp.parentNode; if (n == root) break; // visit n if (n.nodeType == 3) s += n.nodeValue.replace(/\s/, ""); // done visit n tmp = n; n = n.nextSibling; } while (n == null) } c = n; } while (c != root); return s; }
If you want to do something else with the visited node, just change the code between visit and done visit usind the variable c or n with your own dom-dosomething function. Because of the use of nextsibling/firstchild, this code should work on almost all browser out there which support dom+it should even work if you modify the dom tree on your way.
