Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Iterations, anyone? AKA How I wrote a walk_dom method.

View walk_dom.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
// 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);

How about less ROFLS and more WALKR?

Owner
cowboy commented

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.