Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate a selector for an element.
// Create a path to an element of the form 2/1/1/34 (index of each child)
function getDomPath(el) {
const stack = [];
while (el.parentNode != null) {
console.log(el.nodeName);
let sibCount = 0;
let sibIndex = 0;
for (let i = 0; i < el.parentNode.childNodes.length; i++) {
const sib = el.parentNode.childNodes[i];
if (sib === el) {
sibIndex = sibCount;
break;
}
if (sib.nodeType === Node.ELEMENT_NODE) {
sibCount++;
}
}
stack.unshift(sibIndex + 1); // +1 because 1-indexing of :nth-child() expresssions
el = el.parentNode;
}
// Exclude the root
return stack.slice(1).join('/');
}
// Take a path (e.g., 1/2/1/11/30), and generate a CSS selector
function generateSelector(path) {
return ':root > ' + path.split('/').map(idx => `:nth-child(${idx})`).join(' > ');
}
function test(element) {
const path = getDomPath(element);
const selector = generateSelector(path);
const found = document.querySelector(selector);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment