Find all CSS rules that apply to an element

后端 未结 9 984
温柔的废话
温柔的废话 2020-11-22 10:26

Many tools/APIs provide ways of selecting elements of specific classes or IDs. There\'s also possible to inspect the raw stylesheets loaded by the browser.

However,

9条回答
  •  误落风尘
    2020-11-22 10:58

    Here's a version of S.B.'s answer which also returns matching rules within matching media queries. I've removed the *.rules || *.cssRules coalescence and the .matches implementation finder; add a polyfill or add those lines back in if you need them.

    This version also returns the CSSStyleRule objects rather than the rule text. I think this is a little more useful, since the specifics of the rules can be more easily probed programmatically this way.

    Coffee:

    getMatchedCSSRules = (element) ->
      sheets = document.styleSheets
      matching = []
    
      loopRules = (rules) ->
        for rule in rules
          if rule instanceof CSSMediaRule
            if window.matchMedia(rule.conditionText).matches
              loopRules rule.cssRules
          else if rule instanceof CSSStyleRule
            if element.matches rule.selectorText
              matching.push rule
        return
    
      loopRules sheet.cssRules for sheet in sheets
    
      return matching
    

    JS:

    function getMatchedCSSRules(element) {
      var i, len, matching = [], sheets = document.styleSheets;
    
      function loopRules(rules) {
        var i, len, rule;
    
        for (i = 0, len = rules.length; i < len; i++) {
          rule = rules[i];
          if (rule instanceof CSSMediaRule) {
            if (window.matchMedia(rule.conditionText).matches) {
              loopRules(rule.cssRules);
            }
          } else if (rule instanceof CSSStyleRule) {
            if (element.matches(rule.selectorText)) {
              matching.push(rule);
            }
          }
        }
      };
    
      for (i = 0, len = sheets.length; i < len; i++) {
        loopRules(sheets[i].cssRules);
      }
    
      return matching;
    }
    

提交回复
热议问题