Skip to content

Instantly share code, notes, and snippets.

@loucyx
Last active April 18, 2024 23:50
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 CSS path of given element.
/**
* 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