Dive Into Greasemonkey

Teaching an old web new tricks

4.14. Getting an element's style

It is occasionally useful to get a specific element's actual style, after all CSS rules have been applied. You might naively assume that an element's style property will give you this, but you would be mistaken. That only returns the contents of the element's style attribute. To get the final style (including any styles defined in external stylesheets), you need to use the getComputedStyle function.

To illustrate this, let's create a simple test page. It defines a style for all <p> elements, but then one of the <p> elements overrides that with its style attribute.

<title>Style test page</title>
<style type="text/css">
p { background-color: white; color: red; }
<p id="p1">This line is red.</p>
<p id="p2" style="color: blue">This line is blue.</p>

Example: Get the styles defined by an element's style attribute

var p1elem, p2elem;
p1elem = document.getElementById('p1');
p2elem = document.getElementById('p2');
alert(p1elem.style.color); // will display an empty string
alert(p2elem.style.color); // will display "blue"

That wasn't terribly helpful, and you should never use element.style to get individual styles. (You can use it to set individual styles; see Setting an element's style.)

So what should you use instead? getComputedStyle().

Example: Get the actual style of an element

var p1elem, p2elem, p1style, p2style;
p1elem = document.getElementById('p1');
p2elem = document.getElementById('p2');
p1style = getComputedStyle(p1elem, '');
p2style = getComputedStyle(p2elem, '');
alert(p1style.color); // will display "rgb(255, 0, 0)"
alert(p2style.color); // will display "rgb(0, 0, 255)"

Real examples

← Adding CSS styles
Setting an element's style →