Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created November 21, 2009 21:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboy/240274 to your computer and use it in GitHub Desktop.
Save cowboy/240274 to your computer and use it in GitHub Desktop.
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
Copy link

How about less ROFLS and more WALKR?

@cowboy
Copy link
Author

cowboy commented Jul 8, 2010

Great idea, done!

@cowboy
Copy link
Author

cowboy commented May 9, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment