Uncovering classes and selectors in CSS files that match an element with JavaScript

Trying to explain my idea with an example since it's a bit tricky. Imagine we have this HTML code:

<ul>
  <li id="myli" class="myclass">Hello</li>
</ul>

along with the corresponding CSS:

.myclass{
   color:red;       
}
li.myclass{
   background-color:black;
}
ul li{
   float:left;
}

Now, the goal is to develop a JavaScript function that takes a DomElement as input and retrieves all the matching selectors from the CSS files for that element (similar to the F12 toolbar in Chrome that displays all styles for an element), like this:

var mySelectors = GetSelectorsForElement(document.getElementById("myli"));

and the result stored in mySelectors would be:

[".myclass",
 "li.myclass",
 "ul li"]

Is it possible to accomplish this in JS?

Answer №1

Based on your explanation, it seems that you will already possess the id. If you are also interested in obtaining the classes, consider utilizing the following approach:

window.getMatchedCSSRules(document.getElementById("id"));

Answer №2

If you're looking for an alternative to using the Webkit-native getMatchedCSSRules due to potential browser support issues, give this function a try:

function getCSS(selector) {
    var styleSheets = document.styleSheets;
    var matchedRules = [];
    for (var i = 0; i < styleSheets.length; i++) {
        var rules = styleSheets[i].rules || styleSheets[i].cssRules;
        for (var j = 0; j < rules.length; j++) {
            if (selector === rules[j].selectorText) {
                matchedRules.push(rules[j].cssText);
            }
        }
    }
    return matchedRules;
}

Check it out on JSFiddle: http://jsfiddle.net/HP326/

Inspired by a solution on Stack Overflow

Answer №3

Retrieve the CSS rules that apply to the element with the id "myli".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to stop the react-router from causing the page to refresh

Need assistance with React Router issue I'm working on a project in reactJs using react-router-dom v5. I have set up a default route for routing. <Redirect to={"someComponent"}/> The problem is that when I refresh the page, it auto ...

modify hidden input values with a dropdown menu and the power of jquery

Hey there, I could really use some help with a challenge I'm facing. I'm currently working on an ecommerce website for my girlfriend and incorporating foxycart for handling the cart functionality. However, I'm stuck at a point where I need t ...

Discover the #ID and apply AddClass through the URL in the Navigation Jquery

I am currently in the process of developing a website and I am looking to navigate from one link to another using IDs. Here is an example of what I am trying to achieve: Page Name: index.html <a href= "collection.html#rings">Rings</a> Page N ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

Dnd-kit: item loses its place in line when dragged over Droppable area

I've encountered an issue while using @dnd-kit. The sorting function works smoothly (e.g. when I drag the 1st element, it sorts correctly), but once I reach a droppable element (green Thrash), the sorting breaks and the 1st element snaps back. You ca ...

What is the reason behind JavaScript subtracting the timezone offset for ISO dates when passed into the Date() function?

In my function, I handle different valid date strings to produce a JavaScript Date object. Most strings work as expected, however, when an ISO formatted date (YYYY/MM/DD) is provided, the user's timezone offset is deducted from the date. For example ...

"Looking to access your Express app in a VM from the internet? Here's how

I have an express app running on a Node.js server hosted on Azure Linux VM, and I am looking to access this website from my personal computer. const express = require('express'); const app = express(); app.listen(3000, () => { console.lo ...

Avoiding the opening of a select menu

Is there a way to prevent the dropdown menu from appearing when a select element is clicked in a form? I have attempted two methods but they did not work: $('select').click (function (e) { console.log (e); return false; }); and $(&apo ...

Is it possible to create distinct overlapping divs without using absolute positioning?

I'm seeking assistance in developing the view shown below. I am familiar with using position absolute, but I'm wondering if there is a way to achieve this without relying on absolute values. https://i.sstatic.net/m13cl.png ...

Creating a loading screen with JQuery for an Ajax request

I want to implement a loading screen in my web application every time an ajax call is initiated using jQuery. Currently, I have different types of ajax calls such as $.getJSON, $.post, and $.ajaxFileupload, each with their own Success function that remov ...

Locate an element that is nested within a "concat(" XPATH using Selenium

Embarking on my inaugural project as a Python developer, I am currently in the process of web scraping a retail website. The challenge lies in the fact that the site features infinite scrolling functionality, although at times instead of triggering the inf ...

Converting JSON data types into TypeScript interface data types

Struggling to convert data types to numbers using JSON.parse and the Reviver function. I've experimented with different options and examples, but can't seem to figure out where I'm going wrong. The Typescript interface I'm working with ...

json How to retrieve the first index value in jQuery

As part of my Ajax loop, I am successfully generating JSON and iterating through the results. My goal is to extract only the first index value of JSON which is name. In jQuery, I have the following code: PHP $jsonRows[] = array( "name" => ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

Updating AngularJS: Removing the hashtag using history.pushState()

Struggling to enhance the aesthetics of the URLs in my AngularJS application, I am facing some challenges. While I can access the "/" route without any issues, the "/about" route seems to be out of reach. Please note that the project is situated at (loc ...

My AngularJS ng-show functionality is not functioning as expected. I have already reviewed the syntax and still encountering issues

Having trouble with my ng-show, it's not functioning as expected <div class="form-group"> <label class="control-label col-sm-4">NotesTest:</label> <div class="col-sm-4"> <textarea class="form-control ...

Combining Strings and Integers in Javascript

Currently, I am facing a frustrating syntax issue with my code. I am using Scissors, a Node Module for managing pdf files. The documentation describes the syntax for selecting specific pages of the Pdf: var scissors = require('scissors'); var p ...

What causes the error message "ng-model is undefined"?

Within my form, there are three angular-ui-bootstrap typehead elements <form> <div class="form-group"> <label for="fieldname" class="col-md-3 control-label">Name</label> <div class="col-md-6"> <input type="text ...

My CSS seems to be causing an issue and preventing the function from running correctly. Now I just need to

I'm currently working on a project and following a tutorial to help me create a navigation bar. The tutorial I am using can be found here: https://www.youtube.com/watch?v=gXkqy0b4M5g. So far, I have only reached the 22:05 mark in the video. I have su ...

Position the link to the right of the menu using CSS styling

I'm attempting to position a link next to my menu using CSS, but due to my limited experience with CSS I'm struggling to achieve the desired result. Currently, the link appears at the bottom left of the menu section. The code for the menu and lin ...