Generate CSS Selector for Target Element in JavaScript
Last Updated :
15 Apr, 2025
When we are working with web development, applying the styles to the elements dynamically is very common for creating interactive web pages. To apply the styles dynamically to the elements, it is very essential to understand the CSS selectors.
What is a CSS Selector?
A CSS selector is a pattern used to select and style a target HTML element based on their attributes, such as tag name, class, ID, or attributes. CSS selectors provide a feature to target a specific element or a group of elements and apply style to them.
Using the Traversing DOM Tree Method
In this method, we traverse the Document Object Model (DOM) tree from the target element to the root element using the "parentElement" property. During each iteration, we construct a CSS selector segment for each element based on its tag name, class, and ID. Finally, after all iterations, we concatenate all segments to form a final CSS selector for the target element.
Example: In this example, we generate a CSS selector for a HTML div element, and then by using it we'll change the text color.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Example 1</title>
<meta charset="UTF-8" />
</head>
<body>
<div class="container">
<section id="content">
<div class="row">
<div class="col-md-6">
<div id="targetElement">
This is the target element
</div>
</div>
</div>
</section>
</div>
<script src="script.js"></script>
</body>
</html>
JavaScript
// script.js
// function to generate CSS Selector
function generateCSSSelector(element) {
let selector = "";
while (element.parentElement) {
let tagName = element.tagName.toLowerCase();
let classNames = Array.from(element.classList).join(".");
let id = element.id ? "#" + element.id : "";
let segment = tagName + id + (classNames ? "." + classNames : "");
selector = segment + " " + selector;
element = element.parentElement;
}
selector = selector.trim();
return selector;
}
// function to apply styles to the target element
function applyStylesToTarget(cssSelector) {
let targetElement = document.querySelector(cssSelector);
if (targetElement) {
targetElement.style.color = "red";
} else {
console.error("Target element not found using CSS selector:", cssSelector);
}
}
// calling the functions
let targetElement = document.getElementById("targetElement");
let cssSelector = generateCSSSelector(targetElement);
console.log("CSS Selector:", cssSelector);
applyStylesToTarget(cssSelector);
Output:

Using jQuery Method
jQuery is a powerful JavaScript library that provide us a simplified way for DOM manipulation. Here we use jQuery's $() function to select the target element by passing its ID or any other selector. Then we use jQuery methods to traverse up the DOM tree and construct a CSS selector for the element.
Example: In this example, we will use jQuery to generate a CSS selector and use it to create some styles on our target element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Devbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div class="container">
<section id="content">
<div class="row">
<div class="col-md-6">
<div id="targetElement">
This is the target element
</div>
</div>
</div>
</section>
</div>
<script type="text/javascript"
src=
"https://code.jquery.com/jquery-1.7.1.min.js">
</script>
<script src="script.js"></script>
</body>
</html>
JavaScript
// script.js
// Function to apply CSS styles to the target element
// using the generated selector
function applyStylesToTarget(cssSelector) {
let targetElement = $(cssSelector)[0];
if (targetElement) {
$(targetElement).css({
backgroundColor: "lightblue",
color: "red",
padding: "10px",
});
} else {
console.error("Target element not found using CSS selector:",
cssSelector);
}
}
let targetElement = $("#targetElement")[0];
// generating CSS selector
let cssSelector = $(targetElement)
.parents()
.map(function () {
let selector = this.tagName.toLowerCase();
if (this.id) {
selector += "#" + this.id;
return selector;
} else if (this.className) {
selector += "." + this.className.trim().replace(/\s+/g, ".");
return selector;
}
return selector;
})
.get().reverse().join(" > ");
console.log("CSS Selector:", cssSelector);
applyStylesToTarget(cssSelector);
Output:
output for example 2
Similar Reads
How to select DOM Elements in JavaScript ? Selecting DOM (Document Object Model) elements is a fundamental aspect of web development with JavaScript. It allows developers to interact with and manipulate elements on a webpage dynamically. Proper selection of elements is crucial for tasks such as updating content, adding event listeners, or mo
3 min read
How to Select an Element by ID in JavaScript ? In JavaScript, we can use the "id" attribute to interact with HTML elements. The "id" attribute in HTML assigns a unique identifier to an element. This uniqueness makes it easy for JavaScript to precisely target and manipulate specific elements on a webpage. Selecting elements by ID helps in dynamic
2 min read
How To Get Element By Class Name In JavaScript ? When working with the DOM in JavaScript, selecting elements by their class names is a common task. JavaScript provides several methods to achieve this, whether we need to select one or multiple elements. In this article, we will cover different approaches to get elements by class name in JavaScript.
3 min read
How to find the position of HTML elements in JavaScript ? In this article, we are given an HTML document and the task is to get the position of any element by using JavaScript. Use the following steps to get the position: Step 1: Selecting an element: Before finding the position, it is necessary to select the required HTML element. Every element in HTML is
3 min read
How to create an element from a string in JavaScript ? In this article, we will learn how to create an element from a string using JavaScript. This can be used in situations where dynamically generated elements are required by the user. This can be achieved using many approaches as given below: Table of Content Using the createElement() methodUsing the
3 min read
How to create a function `generateSelector` to generate CSS selector path of a DOM element ? 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
5 min read