Skip to content

Instantly share code, notes, and snippets.

@ErikHellman
Last active January 10, 2019 06:57
Show Gist options
  • Save ErikHellman/b325036d47b0b49486be9c3e31296351 to your computer and use it in GitHub Desktop.
Save ErikHellman/b325036d47b0b49486be9c3e31296351 to your computer and use it in GitHub Desktop.
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