Skip to content

Instantly share code, notes, and snippets.

@cowboy cowboy/walk_dom.js
Created Nov 21, 2009

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

mathiasbynens commented Jul 8, 2010

How about less ROFLS and more WALKR?

@cowboy

This comment has been minimized.

Copy link
Owner Author

cowboy commented Jul 8, 2010

Great idea, done!

@cowboy

This comment has been minimized.

Copy link
Owner Author

cowboy commented May 9, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.