Simple HTML DOM Treewalk in Javascript

// non-query dom functions used
//   .nextElementSibling - property has the next sibling
//   .children - property has all children
//   .parentNode - property contains parent element
// Algorithm:
//   to move to the next element in the tree
//     if there are children: move down to the first child
//     if there are siblings: move to the next one
//     if there are no siblings: move up until on a level with siblings, them move to the next sibling
//   Called repeateedly with the current node, this performs a pre-order traversal.
function moveNext(elem) {
    // if there is a child, move down
    // children returns child elements, but not text nodes
    if (elem.children.length) return elem.children[0];

    // if there is a sibling, move across
    if (elem.nextElementSibling) return elem.nextElementSibling;

    // move up to the first sibling of the next parent with a sibling
    next = elem.parentNode;
    while (next && !(next.nextElementSibling)) next = next.parentNode;

    // if we found a parent with a sibling, return the sibling
    if (next) return next.nextElementSibling;

    // else we have walked the whole tree, return null to indicate completion
    return null;    // which is also what next is


Leave a Reply