Skip to content

Instantly share code, notes, and snippets.

@loucyx
Last active October 8, 2025 00:42
Show Gist options
  • Save loucyx/897b9f331d2425fc9ab37d4fcb1a39ea to your computer and use it in GitHub Desktop.
Save loucyx/897b9f331d2425fc9ab37d4fcb1a39ea to your computer and use it in GitHub Desktop.
Get specific CSS path of given element.
/**
* 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