Created
November 12, 2020 03:41
-
-
Save hassanabbasi/14f5edcf1ad5060e77b6ba2b9c110d2d to your computer and use it in GitHub Desktop.
Get the DOM path for any given HTML 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(element) { | |
var path = '', i, tag, selector, className, childIndex, childrenOfParent; | |
for (; element && element.nodeType == 1; element = element.parentNode) { | |
tag = element.tagName.toLowerCase(); | |
className = element.className.trim(); | |
childrenOfParent = $(element.parentNode).children(); | |
childIndex = childrenOfParent.length > 1 ? (childrenOfParent.index(element) + 1) : null; | |
// Don't need to include <html> and <body> tags | |
if (tag === "html" || tag === "body") | |
continue; | |
if (element.id !== '') { | |
// If ID is set for the element, that is it. | |
// Use the ID directly | |
selector = '#' + element.id; | |
// Don't need to look for any parents any further | |
return selector + (path ? (' > ' + path) : ''); | |
} else if (className.length > 0) { | |
// If className is set for the element, use the element tag | |
// along with the className | |
selector = tag + '.' + className.replace(/\s+/g , "."); | |
} else { | |
// Fallback to the tag itself | |
selector = tag; | |
} | |
if (childIndex !== null) { | |
selector += ':nth-child(' + childIndex + ')'; | |
} | |
path = selector + (path ? (' > ' + path) : ''); | |
} | |
return path; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment