DOM Reading and changing styles from a stylesheet


Example

element.style only reads CSS properties set inline, as an element attribute. However, styles are often set in an external stylesheet. The actual style of an element can be accessed with window.getComputedStyle(element). This function returns an object containing the actual computed value of all the styles.

Similar to the Reading and changing inline styles example, but now the styles are in a stylesheet:

<div id="element_id">abc</div>
<style type="text/css">
    #element_id {
        color:blue;
        width:200px;
    }
</style>

JavaScript:

var element = document.getElementById('element_id');

// read the color
console.log(element.style.color); // '' -- empty string
console.log(window.getComputedStyle(element).color); // rgb(0, 0, 255)

// read the width, reset it, then read it again
console.log(window.getComputedStyle(element).width); // 200px
element.style.width = 'initial';
console.log(window.getComputedStyle(element).width); // 885px (for example)