0

I cannot get the colour of an html element using javascript until after it has been set in the script. For example:

<html>
<head>
    <style media="screen" type="text/css">
        h1 {
            color: purple;
        }
    </style>
    <script type="text/javascript">
        function test() {
            var header = document.getElementsByTagName("h1")[0];
            alert("Colour: " + header.style.color); // Does not get the correct colour
            header.style.color = "yellow";
            alert("Colour: " + header.style.color); // Gets the correct colour
        }
    </script>
</head>
<body onload="test();">
    <h1>Header</h1>
</body>
</html>

I would expect the first alert to show "Colour: purple" as set in the css and the second to show "Colour: yellow" from the function itself. However, the first alert simply shows "Colour: ". In both cases, the colour of the element is correct and verified using firebug.

Gaz01
  • 11
  • 3
  • 2
    possible duplicate of [How to get an HTML element's style values in javascript?](http://stackoverflow.com/questions/2664045/how-to-get-an-html-elements-style-values-in-javascript) – Martin Jun 07 '15 at 11:42

2 Answers2

2

element.style.property gets only CSS properties assigned directly on the element. To get the actual property value no matter where it was assigned (external stylesheet or inline) use window.getComputedStyle(element).property, where element is a reference to your element.

So in your example it would be:

alert("Colour: " + getComputedStyle(header).color);

See definition: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

Tigran
  • 2,800
  • 1
  • 19
  • 19
  • Thank you, this lead me in the correct direction. For anybody else finding this, there is a closing braket missing before the semi-colon. – Gaz01 Jun 07 '15 at 12:13
  • Almost - this is what worked for me - alert("Colour: " + window.getComputedStyle(header).color); – Gaz01 Jun 07 '15 at 12:19
1

For elements that are styled via CSS, to get their rendered style, you need to use getComputedStyle.

alert(getComputedStyle(header).color) // the color you want
Leo
  • 13,428
  • 5
  • 43
  • 61