back to series

Implement a generateNthSelector function

The :nth-child() CSS selector is used to target elements based on their position within a parent element. It allows you to select elements that are the nth child of their parent, where “n” can be a specific number, a keyword, or a formula.

Let’s consider the following HTML document, for ease of understanding.

./src/index.html
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./src/index.css" />
<title>Document</title>
</head>
<body>
<div id="root">
<div class="1">
<div class="2">
<p>This is some paragraph</p>
<div class="3">
<button id="btn1">Click me!</button>
<button id="target">Click me!</button>
</div>
</div>
</div>
</div>
</body>
</html>

1. Basic implementation

Given a target and a root element, we need to generate the exact nth-child CSS selector from root till target. You can consider the HTML document given above as the reference.

./src/generateNthSelector.js
function generateNthSelector(rootEl, targetEl) {
const selectors = [];
// the first selctor is generated from the root
const rootItemSelector = `${rootEl.tagName.toLowerCase()}[id=${rootEl.getAttribute('id')}]`;
while (targetEl != rootEl) {
const targetParentEl = targetEl.parentElement;
// nth-child(n) starts from 1
const indexOfTarget = Array.from(targetParentEl.children).indexOf(targetEl) + 1;
// since we are going from target to parent, we need to insert the selectors in reverse order
selectors.unshift(`${targetEl.tagName.toLowerCase()}:nth-child(${indexOfTarget})`);
// the new target will be the parent element
targetEl = targetParentEl;
}
selectors.unshift(rootItemSelector);
return selectors.join('>');
}
const rootEl = document.getElementById('root');
const targetEl = document.getElementById('target');
const output = generateNthSelector(rootEl, targetEl);
/**
* Yields:
* div[id=root]>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>button:nth-child(2)
*/
console.log(output);

Further Reading

I strongly encourage you to explore and tackle additional questions in my Recursion Questions for Frontend Interviews blog series.

By doing so, you can enhance your understanding and proficiency with recursion, preparing you to excel in your upcoming frontend interviews.

Wishing you best. Happy Interviewing 🫡.