Not thoroughly tested, but an alternative to the code in Build the querySelector string value of any given node in the DOM
Note: that code assumes well written HTML, i.e unique ID's - unfortunately, the web is full of rubbish pages that have non-unique ID's, therefore that code will fail
The result may well be a longer selector than the above code, but it seems to work - I've yet to break it :p
function getCSSPath(el) {
const fullPath = [];
const fn = el => {
let tagName = el.tagName.toLowerCase();
let elPath = '';
if (el.id) {
elPath += '#' + el.id;
}
if (el.classList.length) {
elPath += '.' + [...el.classList].join('.');
}
if (el.parentElement) {
if (el.previousElementSibling || el.nextElementSibling) {
let nthChild = 1;
for (let e = el.previousElementSibling; e; e = e.previousElementSibling, nthChild++);
tagName += `:nth-child(${nthChild})`;
}
fn(el.parentElement);
}
fullPath.push(tagName + elPath);
};
fn(el);
return fullPath.join('>');
}
I think this is better version of above though:
function getCSSPath(el) {
let elPath = el.tagName.toLowerCase();
if (el.parentElement && (el.previousElementSibling || el.nextElementSibling)) {
let nthChild = 1;
for (let e = el.previousElementSibling; e; e = e.previousElementSibling, nthChild++);
elPath += `:nth-child(${nthChild})`;
}
if (el.id) {
elPath += '#' + el.id;
}
if (el.classList.length) {
elPath += '.' + [...el.classList].join('.');
}
return (el.parentElement ? getCSSPath(el.parentElement) + '>' : '') + elPath;
}