Last active
December 15, 2015 20:09
-
-
Save JamieLottering/5316939 to your computer and use it in GitHub Desktop.
Detect identical nodes using the node's position
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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