Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get All Defined CSS Selectors for a given DOM Element?

How to get all DEFINED CSS Selectors for a given DOM Element using jQuery?

With defined I mean all CSS Selectors which are used in any of the Stylesheets applied to the document.

In a way, this is similar to the feature implemented by FireBug where in it shows all the Applied CSS Selectors for a selected DOM Element.

Any help is appreciated.

like image 980
GeekTantra Avatar asked Feb 27 '11 20:02

GeekTantra


People also ask

How do I find the CSS selector of an element?

Simply right click and click Inspect Element. This will bring up the CSS selectors for that element.

What does the querySelectorAll () method do?

Document.querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.


1 Answers

From this answer you might be able to get what you are looking for by looping through the cssRules property.

var myElement = $("#content");
for (var x = 0; x < document.styleSheets.length; x++) {
    var rules = document.styleSheets[x].cssRules;
    for (var i = 0; i < rules.length; i++) {
        if (myElement.is(rules[i].selectorText)) {
            $("ul").append("<li>" + rules[i].selectorText + "</li>");
        }
    }
}

Given the following dom:

<div>
    <div id="content">
    </div>
</div>

And css rules:

div
{
    background-color:black;
}
#content{
    height:50px;
    width:50px;
}
div > div
{
    border: solid 1px red;
}

We would get a matched rule set of:

body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form,fieldset, input, textarea, p,
blockquote, th, td div
#content 
div > div

Example on jsfiddle. Not sure how well this will work for all scenarios but might be something to look at if it will fit your needs.

Updated with a slightly more complete example...

$(document).click(function(event) {
    var rules = GetAppliedCssRules($(event.target));
    var $ul = $("#rules").empty();
    $.each(rules, function() {
        $ul.append("<li>" + this + "</li>");
    });
    event.preventDefault();
});

function GetAppliedCssRules($element) {
    var appliedRules = [];
    for (var x = 0; x < document.styleSheets.length; x++) {
        var rules = document.styleSheets[x].cssRules;
        for (var i = 0; i < rules.length; i++) {
            if ($element.is(rules[i].selectorText)) {
                appliedRules.push(rules[i].selectorText);
            }
        }
    }
    return appliedRules;
}
like image 52
Mark Coleman Avatar answered Sep 20 '22 01:09

Mark Coleman