Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all CSS rules that apply to an element

Tags:

javascript

css

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, for browsers to render an element, they'll compile all CSS rules (possibly from different stylesheet files) and apply it to the element. This is what you see with Firebug or the WebKit Inspector - the full CSS inheritance tree for an element.

How can I reproduce this feature in pure JavaScript without requiring additional browser plugins?

Perhaps an example can provide some clarification for what I'm looking for:

<style type="text/css">     p { color :red; }     #description { font-size: 20px; } </style>  <p id="description">Lorem ipsum</p> 

Here the p#description element have two CSS rules applied: a red color and a font size of 20 px.

I would like to find the source from where these computed CSS rules originate from (color comes the p rule and so on).

like image 703
cgbystrom Avatar asked Jun 01 '10 19:06

cgbystrom


People also ask

How do I find the CSS of an element?

The CSS of an element can be obtained using the getComputedStyle element function in JavaScript. It returns a JavaScript object containing CSS properties and their values. This object is indexed and iterable over the property names. The getPropertyValue(property) is used to get the value of a property.

What selector applies a rule to all elements?

The universal selector, written "*", matches the name of any element type.

What are the 3 CSS rules?

Inheritance, the Cascade, and Specificity are the big three. Understanding these concepts will allow you to write very powerful stylesheets and also save time by writing fewer CSS rules.

What order are CSS rules applied?

CSS rules always prioritize from left to right, then from top to bottom.


1 Answers

Since this question currently doesn't have a lightweight (non-library), cross-browser compatible answer, I'll try to provide one:

function css(el) {     var sheets = document.styleSheets, ret = [];     el.matches = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector          || el.msMatchesSelector || el.oMatchesSelector;     for (var i in sheets) {         var rules = sheets[i].rules || sheets[i].cssRules;         for (var r in rules) {             if (el.matches(rules[r].selectorText)) {                 ret.push(rules[r].cssText);             }         }     }     return ret; } 

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

Calling css(document.getElementById('elementId')) will return an array with an element for each CSS rule that matches the passed element. If you want to find out more specific information about each rule, check out the CSSRule object documentation.

like image 129
S.B. Avatar answered Sep 22 '22 15:09

S.B.