Skip to content

Instantly share code, notes, and snippets.

@JamieLottering
Last active December 15, 2015 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamieLottering/5316939 to your computer and use it in GitHub Desktop.
Save JamieLottering/5316939 to your computer and use it in GitHub Desktop.
Detect identical nodes using the node's position
// Ignore whitespace && body nodes
function shouldIgnoreNode(node) {
return (node.nodeName === 'BODY' || node.nodeType === 8 || node.nodeType === 3);
}
// Safely walk up previousSibling nodes by ignoring whitespace nodes
function getPrevNode(node) {
var sibling = node.previousSibling;
if (!sibling) {
return null;
}
if (shouldIgnoreNode(sibling)) {
return getPrevNode(sibling);
}
return sibling;
}
// Given a node, return the position as an array where
// the keys equal the nodes position in the tree relative to siblings/parents
function parse(node) {
var rtn = [];
var count = 0;
if (shouldIgnoreNode(node)) {
return rtn;
}
var prevSibling = node.previousSibling;
var parentNode = node.parentNode;
if (prevSibling !== null) {
while(prevSibling = getPrevNode(prevSibling)) {
count++;
}
rtn.push(count);
}
if (!prevSibling && parentNode !== null) {
rtn = rtn.concat(parse(parentNode));
}
return rtn;
}
// Given a target node, generate an array indicating its position relative
// to the root node. Reverse the output so we can 'climb' back down the tree
function buildTreeMap(element) {
var treeMap = parse(element);
return treeMap.reverse();
}
var element = document.getElementById('me');
var map = buildTreeMap(element);
console.log(map);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment