Is it possible to find CSS rules from an HTML node via JavaScript?

前端 未结 5 1295
深忆病人
深忆病人 2020-12-09 21:49

I want to get an element in the DOM and then lookup what rules in my CSS file(s) are contributing to it\'s appearance. Similar to what firebug or webkits inspector does. Is

5条回答
  •  余生分开走
    2020-12-09 22:27

    This is what you want. WebKit only. I found out about getMatchedCSSRules by looking at the chromium web inspector source.

      function getAppliedSelectors(node) {
        var selectors = [];
        var rules = node.ownerDocument.defaultView.getMatchedCSSRules(node, '');
    
        var i = rules.length;
        while (i--) {
          selectors.push(rules[i].selectorText);
        }
        return selectors;
      }
    

提交回复
热议问题