Skip to content

@cowboy /walk_dom.js
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Iterations, anyone? AKA How I wrote a walk_dom method.
// Iterations, anyone? AKA
// How I wrote a walk_dom method.
//
// A JavaScript poem by
//
// "Cowboy" Ben Alman
// 11/21/2009
// A starting point.
function walk_dom( node, callback ) {
var cur = node, skip;
do {
if ( !skip && cur.firstChild ) {
cur = cur.firstChild;
} else if ( cur.nextSibling ) {
cur = cur.nextSibling;
} else {
skip = true;
cur = cur.parentNode;
continue;
}
skip = false;
callback( cur );
} while ( cur !== node );
};
// Using a temp variable.
function walk_dom( node, callback ) {
var cur = node, skip, temp;
do {
if ( !skip && ( temp = cur.firstChild ) ) {
cur = temp;
} else if ( temp = cur.nextSibling ) {
cur = temp;
} else {
skip = cur = cur.parentNode;
continue;
}
skip = 0;
callback( cur );
} while ( cur !== node );
};
// Removing that redundant "else if".
function walk_dom( node, callback ) {
var cur = node, skip, temp;
do {
if ( !skip && ( temp = cur.firstChild ) || ( temp = cur.nextSibling ) ) {
skip = 0;
callback( cur = temp );
} else {
skip = cur = cur.parentNode;
}
} while ( cur !== node );
};
// Let the callback skip the current node by returning false.
function walk_dom( node, callback ) {
var cur = node, skip, temp;
do {
if ( !skip && ( temp = cur.firstChild ) || ( temp = cur.nextSibling ) ) {
skip = callback( cur = temp ) === false;
} else {
skip = cur = cur.parentNode;
}
} while ( cur !== node );
};
// Wow, cool! Now I can simplify that if/else into a ternary.
function walk_dom( node, callback ) {
var cur = node, skip, temp;
do {
skip = !skip && ( temp = cur.firstChild ) || ( temp = cur.nextSibling )
? callback( cur = temp ) === false
: cur = cur.parentNode;
} while ( cur !== node );
};
// It's all done now, but just for the sake of argument..
// Organized for smallest minification size.
function walk_dom( node, callback, cur, skip, temp ) {
cur = node;
do {
skip = !skip && ( temp = cur.firstChild ) || ( temp = cur.nextSibling )
? callback( cur = temp ) === !1
: cur = cur.parentNode;
} while ( cur !== node );
};
// Minified!
(function(w,a,l,k,r){l=w;do{k=!k&&(r=l.firstChild)||(r=l.nextSibling)?a(l=r)===!1:l=l.parentNode}while(l!==w)})(node,callback);
@mathiasbynens

How about less ROFLS and more WALKR?

@cowboy
Owner

Great idea, done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.