How to generate unique css selector for DOM element?

This function creates a long, but quite practical unique selector, works quickly.

const getCssSelector = (el) => {
  let path = [], parent;
  while (parent = el.parentNode) {
    path.unshift(`${el.tagName}:nth-child(${[].indexOf.call(parent.children, el)+1})`);
    el = parent;
  }
  return `${path.join(' > ')}`.toLowerCase();
};

Example result:

html:nth-child(1) > body:nth-child(2) > div:nth-child(1) > div:nth-child(1) > main:nth-child(3) > div:nth-child(2) > p:nth-child(2)

The following code creates a slightly more beautiful and short selector

const getCssSelectorShort = (el) => {
  let path = [], parent;
  while (parent = el.parentNode) {
    let tag = el.tagName, siblings;
    path.unshift(
      el.id ? `#${el.id}` : (
        siblings = parent.children,
        [].filter.call(siblings, sibling => sibling.tagName === tag).length === 1 ? tag :
        `${tag}:nth-child(${1+[].indexOf.call(siblings, el)})`
      )
    );
    el = parent;
  };
  return `${path.join(' > ')}`.toLowerCase();
};

Example result:

html > body > div > div > main > div:nth-child(2) > p:nth-child(2)

Check this CSS selector generator library @medv/finder

Build Status

  • Generates shortest selectors
  • Unique selectors per page
  • Stable and robust selectors
  • 2.9 kB gzip and minify size

Example of generated selector:

.blog > article:nth-child(3) .add-comment