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

前端 未结 2 1062
灰色年华
灰色年华 2021-01-31 22:58

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

相关标签:
2条回答
  • 2021-01-31 23:28

    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;
    }
    
    0 讨论(0)
  • 2021-01-31 23:45

    I think the two features are not similar.

    Furthermore, I think nor jQuery nor the browser keep trace of selectors used through javascript code or stylesheet file; selectors are used to reference one or more DOM elements, to eventually apply styles to them.

    So, what it is kept are the styles, not the used selectors.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题