Created
November 19, 2013 12:24
-
-
Save karlgroves/7544592 to your computer and use it in GitHub Desktop.
Get DOM path of an element
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
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 | |
} | |
//Usage: | |
var path = getDomPath(document.getElementById('button')); | |
console.log(path.join(' > ')); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In case anyone needs an updated version of this, here's what I have:
Changes:
:eq(n)
, so I changed it to:nth-type(n)
and filtered the list of siblings for the same node type, then incrementn
in the beginning of the for loop instead of after (since nth-child and nth-type starts at 1, not 0).#123-div
to[id="123-div"]
to avoid an error (more: https://mathiasbynens.be/notes/css-escapes)I'm sure there's plenty of room for improvement, but this works great for me in Chrome (I use it a lot for Tampermonkey scripts).