How to create a function `generateSelector` to generate CSS selector path of a DOM element ?
Last Updated :
23 Jul, 2025
In this article, we will learn about CSS selectors, and we will also implement a `generateSelector()` function that returns a string value to provide a valid selector to a target DOM element.
What is a CSS Selector?
A CSS selector is used to select a group of elements (or nodes in the DOM tree) that follow a certain pattern.
Example: Here is an example of CSS selectors.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
/* h2 selector selects all the h2
elements present in body */
h2 {
background-color: red;
}
/* div > h3 selector selects all the
h3 elements which are direct
descendants of div */
div>h3 {
background-color: blue;
}
</style>
</head>
<body>
<h2>Welcome To GFG</h2>
<div>
<h3>Hello World!</h3>
</div>
</body>
</html>
Output:
Code output
Understanding the outline concept behind generateSelector() Function: Now, let's talk about how to create a `generateSelector()` function which returns a valid selector string to a target DOM element that presents inside a DOM tree. For a better understanding, let's take a look at some of the examples of the function and its expected response.
Example: Here is the implementation of the above-explained method.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h2>Welcome To GFG</h2>
<div>
<h3>Hello World!</h3>
<div>
<p>Some random text</p>
</div>
</div>
<script>
let target = document.querySelector('h3');
generateSelector(target);
// Expected output -
//"HTML > BODY:nth-child(2) > DIV:nth-child(3) > H3"
target = document.querySelector('h2');
generateSelector(target);
// "HTML > BODY:nth-child(2) > H2:nth-child(2)"
target = document.querySelector('p');
generateSelector(target);
// "HTML > BODY:nth-child(2) > DIV:nth-child(3)
// > DIV:nth-child(2) > P"
</script>
</body>
</html>
The above code is just a pseudo code that does not have the implementation of the generateSelector function. It is only there to help you understand what the function is for. We are going to implement this function down below in the next section -
Expected Output:
HTML > BODY:nth-child(2) > DIV:nth-child(3) > H3
HTML > BODY:nth-child(2) > H2:nth-child(2)
HTML > BODY:nth-child(2) > DIV:nth-child(3) > DIV:nth-child(2) > P
Example: Implementing `generateSelector()` function: Now, we have a good grasp on what the `generateSelector` function is, let's try to implement it -
HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h2>Welcome To GFG</h2>
<div>
<h3>Hello World!</h3>
<div>
<p>Some random text</p>
</div>
</div>
<script>
// Let's write a generateSelector() function
// that should return selector path to h3
// inside the div
const generateSelector = (target) => {
const selectorPath = [];
while (target.tagName) {
let i = 0;
if (target.parentNode) {
const children = target.parentNode.children;
while (i < children.length && children[i] !== target) {
i++;
}
}
selectorPath.unshift(target.nodeName + (
i > 0 ? `:nth-child(${i + 1})` : ''));
target = target.parentNode;
}
return selectorPath.join(' > ');
}
let target = document.querySelector('h3');
console.log(generateSelector(target));
// Expected output -
// "HTML > BODY:nth-child(2) > DIV:nth-child(3) > H3"
target = document.querySelector('h2');
console.log(generateSelector(target));
// "HTML > BODY:nth-child(2) > H2:nth-child(2)"
target = document.querySelector('p');
console.log(generateSelector(target));
// "HTML > BODY:nth-child(2) > DIV:nth-child(3)
// > DIV:nth-child(2) > P"
</script>
</body>
</html>
Let's break the above code step by step -
- We create a selectorPath array to store selector elements in reverse order (as we bubble up the DOM tree from the target element)
- We run a loop to travel up the DOM tree until we reach a NULL, i.e. until the root of the DOM tree is traversed.
- We run through the children of the target's parentNode until we reach the target itself. This is done so as to determine the index of the target among its parent's children so that we can add it to the selector.
- We update the selectorPath array with the current selector path value and also update the target to its parentNode.
- We continue doing the same until the whole DOM tree is traversed.
- After the loop is over, we join the selectorPath array elements together with ' > ' as a concatenate symbol, which signifies a child of a parent is a CSS selector.
- The resultant string is the final CSS selector string that we were looking for.
Output:
Code output
Example 2: In this example, we are implemented in the same way as Example 1, but it has different child elements in the body tag, so the different outputs get logged to the console.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Welcome to GFG</h1>
<div>
<h2>Random text</h2>
<button>Click me</button>
<p>Hello world</p>
</div>
<script>
// Let's write a generateSelector() function
// that should return selector path to h3
// inside the div
const generateSelector = (target) => {
const selectorPath = [];
while (target.tagName) {
let i = 0;
if (target.parentNode) {
const children = target.parentNode.children;
while (i < children.length && children[i] !== target) {
i++;
}
}
selectorPath.unshift(target.nodeName +
(i > 0 ? `:nth-child(${i + 1})` : ''));
target = target.parentNode;
}
return selectorPath.join(' > ');
}
let target = document.querySelector('h1');
console.log(generateSelector(target));
target = document.querySelector('h2');
console.log(generateSelector(target));
target = document.querySelector('button');
console.log(generateSelector(target));
target = document.querySelector('p');
console.log(generateSelector(target));
</script>
</body>
</html>
Output:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is an Operating System? An Operating System is a System software that manages all the resources of the computing device. Acts as an interface between the software and different parts of the computer or the computer hardware. Manages the overall resources and operations of the computer. Controls and monitors the execution o
9 min read