Created
December 5, 2013 15:37
-
-
Save uniqname/7807654 to your computer and use it in GitHub Desktop.
Find a path from one node to another
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
var getPath = function (start, end) { | |
var getParents = function (el) { | |
var parents = [el]; | |
el = el.parentElement; | |
while (el.parentElement) { | |
parents.push(el = el.parentElement); | |
} | |
return parents; | |
}, | |
intersection = function (a, b) { | |
var shorter = (a.length < b.length) ? a : b, | |
longer = (shorter === a) ? b : a, | |
shorterLen = shorter.length, | |
intersection = [], | |
i; | |
for (i = 0; i < shorterLen; i++) { | |
if (longer.indexOf(shorter[i]) >= 0 ) { | |
intersection.push(shorter[i]); | |
} | |
} | |
return intersection; | |
}, | |
getSelectorPath = function (ancestry) { | |
var i, len, _ref, nodeName, selPath = []; | |
for (i = 0, len = ancestry.length; i < len; i++) { | |
_ref = ancestry[i]; | |
nodeName = _ref.nodeName; | |
selPath.push(nodeName.toLowerCase() + (_ref.id ? '#' + _ref.id : '') + (_ref.className ? '.' + _ref.className.split(' ').join('.') : '')); | |
} | |
return selPath; | |
}, | |
parentsA = getParents(start), | |
parentsB = getParents(end), | |
commonParent = intersection(parentsA, parentsB)[0], | |
pathA, pathB; | |
parentsA = parentsA.slice(0, parentsA.indexOf(commonParent) + 1); | |
parentsB = parentsB.slice(0, parentsB.indexOf(commonParent)); | |
pathA = getSelectorPath(parentsA); | |
pathB = getSelectorPath(parentsB) | |
return { | |
length: pathA.length + pathB.length, | |
path: pathA.join(' < ') + pathB.join(' > ') | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment