back to series Implement a generateNthSelector function May 06, 2024
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.
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
< link rel = "stylesheet" href = "./src/index.css" />
< p >This is some paragraph</ p >
< button id = "btn1" >Click me!</ button >
< button id = "target" >Click me!</ button >
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.
function generateNthSelector ( rootEl , targetEl ) {
// 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);
* div[id=root]>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>button:nth-child(2)
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 🫡.