Skip to content

Instantly share code, notes, and snippets.

@hassanabbasi
Created November 12, 2020 03:41
Show Gist options
  • Save hassanabbasi/14f5edcf1ad5060e77b6ba2b9c110d2d to your computer and use it in GitHub Desktop.
Save hassanabbasi/14f5edcf1ad5060e77b6ba2b9c110d2d to your computer and use it in GitHub Desktop.
Get the DOM path for any given HTML element
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