Find all CSS rules that apply to an element

后端 未结 9 824
温柔的废话
温柔的废话 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 11:07

    Have a look at this library, which does what was asked for: http://www.brothercake.com/site/resources/scripts/cssutilities/

    It works in all modern browsers right back to IE6, can give you rule and property collections like Firebug (in fact it's more accurate than Firebug), and can also calculate the relative or absolute specificity of any rule. The only caveat is that, although it understands static media types, it doesn't understand media-queries.

    0 讨论(0)
  • 2020-11-22 11:10

    EDIT: This answer is now deprecated and no longer works in Chrome 64+. Leaving for historical context. In fact that bug report links back to this question for alternative solutions to using this.


    Seems I managed to answer my own question after another hour of research.

    It's as simple as this:

    window.getMatchedCSSRules(document.getElementById("description"))
    

    (Works in WebKit/Chrome, possibly others too)

    0 讨论(0)
  • 2020-11-22 11:11

    Here is my version of getMatchedCSSRules function which support @media query.

    const getMatchedCSSRules = (el) => {
      let rules = [...document.styleSheets]
      rules = rules.filter(({ href }) => !href)
      rules = rules.map((sheet) => [...(sheet.cssRules || sheet.rules || [])].map((rule) => {
        if (rule instanceof CSSStyleRule) {
          return [rule]
        } else if (rule instanceof CSSMediaRule && window.matchMedia(rule.conditionText)) {
          return [...rule.cssRules]
        }
        return []
      }))
      rules = rules.reduce((acc, rules) => acc.concat(...rules), [])
      rules = rules.filter((rule) => el.matches(rule.selectorText))
      rules = rules.map(({ style }) => style)
      return rules
    }
    
    0 讨论(0)
提交回复
热议问题