CSS Selector Generator

The :nth-child() CSS pseudo-class matches elements based on the indexes of the elements in the child list of their parents. In other words, the :nth-child() selector selects child elements according to their position among all the sibling elements within a parent element.

<div id="root">
  <article>CSS Selector Generator</article>
  <section>
    Section 1<p>P 1</p>
    <p>
      P 2 <span>Span 1</span>
      <span>
        Span 2 <button>Click Me 1</button>
        <button id="target">Click Me 2</button>
      </span>
    </p>
  </section>
  <section>Section 2</section>
</div>
function cssSelectorGenerator(root, target) {
  const selectors = [];
  while (target !== root) {
    let nthChild = Array.from(target.parentNode.children).indexOf(target) + 1;
    let tagName = target.tagName.toLowerCase();
    let selector = tagName + ":nth-child(" + nthChild + ")";
    selectors.unshift(selector);
    target = target.parentNode;
  }
  let rootTag = target.tagName.toLowerCase();
  let rootSelector = rootTag + "[id='" + target.id + "']";
  selectors.unshift(rootSelector);
  return selectors.join(" > ");
}

const root = document.getElementById("root");
const target = document.getElementById("target");
console.log(cssSelectorGenerator(root, target));
// div[id='root'] > section:nth-child(2) > p:nth-child(2) > span:nth-child(2) > button:nth-child(2)