Inherited CSS Values via Javascript

cschear picture cschear · Jul 23, 2009 · Viewed 10.2k times · Source

On my page I am changing some css styles via javascript. When I try and pull a value that has been inherited - it comes up blank. Consider the following:

    .Sliding
    {
        display: none;
        overflow: hidden;
    }

    .Sliding #FilterBox
    {
        height: 185px;
        background-color: Fuchsia;
    }

And the html:

<div class="Sliding" id="FilterBox">
        <h3>Test Form</h3>
        This is a test/<br />
        12345
</div>

If I look at the element 'document.getElementById(objname).style.display' its blank? How can I read the display value via via javascript?

Answer

Quentin picture Quentin · Jul 23, 2009

You'll want to use getComputedStyle.

The .style property is a means of accessing and setting inline style (i.e. like the style attribute).

Note, however, that your example has nothing to do with inheritance. Just rule-sets that apply directly to the elements you are interested in. Inheritance is when an element takes on the same style as its parent via the inherit keyword.

span {
    color: inherit;
}

getComputedStyle will give the final computed value though, so it will pick up inherited values too.