Skip to content

Instantly share code, notes, and snippets.

@scagood
Created January 25, 2018 12:55
Show Gist options
  • Save scagood/3a8cfe2c112a853c67f263c087bdb266 to your computer and use it in GitHub Desktop.
Save scagood/3a8cfe2c112a853c67f263c087bdb266 to your computer and use it in GitHub Desktop.
A simple function to get the CSS style path of an element.
const cssPath = (function () {
function tagUnique(l) {
const es = [].filter.call(
l.parentElement.children,
e => e !== l
);
return -1 === []
.map.call(es, e => e.tagName)
.indexOf(l.tagName);
}
function classUnique(l, tag) {
const es = [].filter.call(
l.parentElement.children,
e => e !== l && !(
tag === true &&
e.tagName !== l.tagName
)
);
return -1 === []
.map.call(es, e => e.className)
.filter(c => c !== '')
.map(c => '.' + c.trim().replace(/\s+/g, '.'))
.indexOf('.' + l.className.trim().replace(/\s+/g, '.'));
}
return el => {
const names = [];
while (el.parentNode) {
if (el.id) {
names.unshift('#' + el.id);
break;
}
if (el == el.ownerDocument.documentElement) {
names.unshift(el.tagName);
}
else if (el.className && classUnique(el, true)) {
names.unshift(
(classUnique(el) ? '' : el.tagName) +
'.' + el.className.trim().replace(/\s+/g, '.')
);
}
else if (tagUnique(el)) {
names.unshift(el.tagName);
}
else {
names.unshift(
el.tagName + ":nth-child(" +
([].indexOf.call(
el.parentElement.children,
el
) + 1) + ")"
);
}
el = el.parentNode;
}
return names.join(" > ");
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment