Last active
April 18, 2024 23:50
-
-
Save loucyx/897b9f331d2425fc9ab37d4fcb1a39ea to your computer and use it in GitHub Desktop.
Get CSS path of given element.
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
/** | |
* Get the CSS path of a given element. | |
* | |
* @param {Element} [element] Element to get the css path to. | |
* @param {string} [path=""] Path so far (used in recursion). | |
*/ | |
export const cssPath = (element, path = "") => | |
((tag, nth) => | |
tag | |
? cssPath( | |
element?.parentElement ?? undefined, | |
`${ | |
element?.id | |
? `${tag}[id="${element.id}"]` | |
: `${tag}${nth > 1 ? `:nth-child(${nth})` : ""}` | |
}${path !== "" ? ">" : ""}${path}`, | |
) | |
: path)( | |
element instanceof Element ? element.tagName.toLowerCase() : "", | |
element instanceof Element && element.parentElement | |
? [...element.parentElement.children].indexOf(element) + 1 | |
: 0, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment