Skip to content

Instantly share code, notes, and snippets.

@malchata
Last active April 4, 2024 09:10
Show Gist options
  • Save malchata/56e92306acb0c5b9fd3541ed16ce2d23 to your computer and use it in GitHub Desktop.
Save malchata/56e92306acb0c5b9fd3541ed16ce2d23 to your computer and use it in GitHub Desktop.
A module that returns a selector string for a DOM node.
// Cribbed this from:
// https://web.dev/debug-web-vitals-in-the-field/#usage-with-the-web-vitals-javascript-library
export function getSelector(node, maxLen = 100) {
let sel = '';
try {
while (node && node.nodeType !== 9) {
const part = node.id ? '#' + node.id : node.nodeName.toLowerCase() + (
(node.className && node.className.length) ?
'.' + Array.from(node.classList.values()).join('.') : '');
if (sel.length + part.length > maxLen - 1) {
return sel || part;
}
sel = sel ? part + '>' + sel : part;
if (node.id) {
break;
}
node = node.parentNode;
}
} catch (e) {
// Do nothing.
}
return sel;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment