Last active
April 4, 2024 09:10
-
-
Save malchata/56e92306acb0c5b9fd3541ed16ce2d23 to your computer and use it in GitHub Desktop.
A module that returns a selector string for a DOM node.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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