1

It's a little hard to explain what I want to do, So I'll try to do it with an example. Lets say I have this HTML:

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

and the following css

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

Now, I want to create a function in JS that get a DomElement and gets all the matching selectors from the css files for this element (like the F12 toolbar in chrome that shows all styles for an element) like the following:

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

and the content of mySelectors will be

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

Can this be achieved in JS?

DorR
  • 645
  • 1
  • 9
  • 22

3 Answers3

2

With the way you described it, it looks like you'll already have the id, if you also wanted to get the classes, you could do something like this:

window.getMatchedCSSRules(document.getElementById("id"));
9er
  • 1,604
  • 3
  • 20
  • 37
  • Note that this is only supported by Webkit browsers, so not IE / Firefox / Opera / etc. – S.B. Mar 25 '14 at 13:40
  • Tried this on this page window.getMatchedCSSRules(document.getElementById("content")) and got null – DorR Mar 25 '14 at 14:02
  • What browser are you running it in? – 9er Mar 25 '14 at 14:20
  • Chrome, that command works but not everytime, can't point on when it is working and when not. But still, when it works, it gives me everything I need. Thanks. – DorR Mar 26 '14 at 09:48
1

If you don't want to use the Webkit-native getMatchedCSSRules because of (lack of) browser support, you could simply try the following function:

function css(a) {
    var sheets = document.styleSheets, o = [];
    for (var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for (var r in rules) {
            if (a.is(rules[r].selectorText)) {
                o.push(rules[r].selectorText);
            }
        }
    }
    return o;
}

JSFiddle: http://jsfiddle.net/HP326/

Adapted from Can jQuery get all CSS styles associated with an element?

Community
  • 1
  • 1
S.B.
  • 2,920
  • 1
  • 17
  • 25
0
window.getMatchedCSSRules(document.getElementById("myli"));
Tuhin
  • 3,335
  • 2
  • 16
  • 27
  • Note that this is only supported by Webkit browsers, so not IE / Firefox / Opera / etc. – S.B. Mar 25 '14 at 13:42