How to generate CSS selector for the target element? | Frontend Interview Question | Advanced JavaScript
@Yomesh Gupta

JavaScriptIntermediate
1213
Do you see value in our efforts?

Devtools Tech is a free platform for Frontend Engineers. It takes a lot of time, effort, and finanical resources to keep the platform running. If you see any value in our work and would like to support us then you can do using the following options.

InternationalDomestic

Given a valid DOM tree and a target element, generate a valid selector to target it.

Example 1:

<div>
    <h1>Devtools Tech</h1>
    <div>
        <p>Subscribe to our YT channel </p>
        <a href="youtube.com/c/devtoolstech">here</a>
    </div>
</div>
const selector = generateSelector(root, target);
console.log(selector); // div > div > a

Example 2:

<section>
    <ul>
        <li>Home</li>
        <li>Services</li>
        <li>Product</li>
    </ul>
</section>
// selecting li with text Product
const selector = generateSelector(root, target);
console.log(selector); // section > ul > li:nth-of-type(3)

There could be more than 1 answer to this question.

Loading IDE...