Skip to content

Instantly share code, notes, and snippets.

@affonso
Forked from karlgroves/gist:7544592
Created February 23, 2019 22:53
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 affonso/d4b38b151d39e6b545c872b46dd146e5 to your computer and use it in GitHub Desktop.
Save affonso/d4b38b151d39e6b545c872b46dd146e5 to your computer and use it in GitHub Desktop.
Get DOM path of an element
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