Find all CSS rules that apply to an element

后端 未结 9 913
温柔的废话
温柔的废话 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条回答
  •  旧时难觅i
    2020-11-22 11:05

    var GetMatchedCSSRules = (elem, css = document.styleSheets) => Array.from(css)
      .map(s => Array.from(s.cssRules).filter(r => elem.matches(r.selectorText)))
      .reduce((a,b) => a.concat(b));
    
    function Go(paragraph, print) {
      var rules = GetMatchedCSSRules(paragraph);
    PrintInfo:
      print.value += "Rule 1: " + rules[0].cssText + "\n";
      print.value += "Rule 2: " + rules[1].cssText + "\n\n";
      print.value += rules[0].parentStyleSheet.ownerNode.outerHTML;
    }
    
    Go(document.getElementById("description"), document.getElementById("print"));
    p {color: red;}
    #description {font-size: 20px;}

    Lorem ipsum

提交回复
热议问题