Open In App

Generate CSS Selector for Target Element in JavaScript

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.

<!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>
// 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:

example1

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.

<!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>
// 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:

example2

output for example 2

Article Tags :