Skip to content

Instantly share code, notes, and snippets.

@stevoland
Created September 13, 2012 11:11
Show Gist options
  • Save stevoland/3713624 to your computer and use it in GitHub Desktop.
Save stevoland/3713624 to your computer and use it in GitHub Desktop.
Get CSS Selector for an element
function getCSSSelector(el) {
var names = [];
while (el.parentNode) {
if (el.id) {
names.unshift('#' + el.id);
break;
} else {
if (el == el.ownerDocument.documentElement) {
names.unshift(el.tagName);
} else {
for (var c=1, e=el; e.previousElementSibling; e=e.previousElementSibling, c++);
names.unshift(el.tagName + ':nth-child(' + c + ')');
}
el = el.parentNode;
}
}
return names.join(' > ');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment