Last active
September 12, 2021 14:25
-
-
Save remoharsono/a68f07e77dbfdd8255825ac230736bba to your computer and use it in GitHub Desktop.
get dom path in pure js that return a jQuery path
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
/* | |
sample usage: | |
var path = getDomPath(element); | |
console.log(path.join(' > ')); | |
output: | |
body > section:eq(0) > div:eq(3) > section#content > section#firehose > div#firehoselist > article#firehose-46813651 > header > h2 > span#title-46813651 | |
taken from: | |
http://stackoverflow.com/questions/5728558/get-the-dom-path-of-the-clicked-a | |
*/ | |
function getDomPath(el) { | |
var stack = []; | |
while ( el.parentNode != null ) { | |
console.log(el.nodeName); | |
var sibCount = 0; | |
var sibIndex = 0; | |
for ( var i = 0; i < el.parentNode.childNodes.length; i++ ) { | |
var sib = el.parentNode.childNodes[i]; | |
if ( sib.nodeName == el.nodeName ) { | |
if ( sib === el ) { | |
sibIndex = sibCount; | |
} | |
sibCount++; | |
} | |
} | |
if ( el.hasAttribute('id') && el.id != '' ) { | |
stack.unshift(el.nodeName.toLowerCase() + '#' + el.id); | |
} else if ( sibCount > 1 ) { | |
stack.unshift(el.nodeName.toLowerCase() + ':eq(' + sibIndex + ')'); | |
} else { | |
stack.unshift(el.nodeName.toLowerCase()); | |
} | |
el = el.parentNode; | |
} | |
return stack.slice(1); // removes the html element | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great, just what I needed!