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.

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this lead me in the correct direction. For anybody else finding this, there is a closing braket missing before the semi-colon.
Almost - this is what worked for me - alert("Colour: " + window.getComputedStyle(header).color);
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.