JSFiddle - React, Tailwind, and code Playground
by Ben Alman
HTML
<script src="https://rawgit.com/cowboy/958000/raw/ba-smallwalker.js"></script>
<a href="https://gist.github.com/958000" target="_top">Small Walker: A small and simple JavaScript DOM walker</a>
<div style="display:none;">
<div id="a"></div>
<div id="a1">x</div>
<div id="b">
<div id="b1"></div>
</div>
<div id="c">
<div id="c1"></div>
<div id="c2">x</div>
</div>
<div id="d">
<div id="d1">
<div id="d1a"></div>
<div id="d1b">x</div>
</div>
<div id="d2"></div>
</div>
<div id="z"></div></div>
<div id="results"></div>
JavaScript
function assert(actual, expected) {
var result = actual.join(',') == expected.join(',');
$('#results').append((result ? 'OK' : 'FAIL') + '<br/>');
}
var arr;
function fn(depth) {
arr.push(depth, this.id || this.nodeValue.replace(/\s+/g, ' '));
}
arr = [];
walk(document.getElementById('a'), fn);
assert(arr, [0, 'a']);
arr = [];
walk(document.getElementById('z'), fn);
assert(arr, [0, 'z'], 'this is why i used depth > 0');
arr = [];
walk(document.getElementById('a1'), fn);
assert(arr, [0, 'a1', 1, 'x']);
arr = [];
walk(document.getElementById('b'), fn);
assert(arr, [0, 'b', 1, ' ', 1, 'b1', 1, ' ']);
arr = [];
walk(document.getElementById('c'), fn);
assert(arr, [0, 'c', 1, ' ', 1, 'c1', 1, ' ', 1, 'c2', 2, 'x', 1, ' ']);
arr = [];
walk(document.getElementById('d'), fn);
assert(arr, [0, 'd', 1, ' ', 1, 'd1', 2, ' ', 2, 'd1a', 2, ' ', 2, 'd1b', 3, 'x', 2, ' ', 1, ' ', 1, 'd2', 1, ' ']);