Last active
October 8, 2025 00:42
-
-
Save loucyx/897b9f331d2425fc9ab37d4fcb1a39ea to your computer and use it in GitHub Desktop.
Get specific CSS path of given element.
This file contains hidden or 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 {Pick<Element, "id" | "parentElement" | "tagName">} [element] Element to get the css path to. | |
* @param {string} [path=""] Path so far (used in recursion). | |
* @returns {string} Full CSS path to the given element | |
*/ | |
export const cssPath = (element, path = "") => { | |
const tagName = element?.tagName ?? "HTML"; | |
const childrenOfType = element?.parentElement | |
? [...element.parentElement.children].filter( | |
(child) => child.tagName === tagName, | |
) | |
: []; | |
const nth = childrenOfType.indexOf(/** @type {Element} */ element) + 1; | |
return `${ | |
element?.id | |
? `#${element.id}` | |
: tagName === "HTML" | |
? "" | |
: cssPath( | |
element?.parentElement ?? undefined, | |
`${tagName.toLocaleLowerCase()}${nth > 1 ? (nth === childrenOfType.length ? ":last-of-type" : `:nth-of-type(${nth})`) : ""}${path !== "" ? ">" : ""}`, | |
) | |
}${path}`; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment