Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get the background color using DOM

I'm trying to get element background style which has been written on a different CSS file. The problem is that I can't get the style which were written in a CSS file.

on the other hand, styling which has been written on the HTML document are possible to get.

CSS code

#try2
{ 
    background-color:yellow;
}
body
{
    background-color:gray;
}
td, th{
    border: 1px solid black;
}

HTML code

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1255" />
        <link rel="stylesheet" type="text/css" href="html.css">
        <script type="text/javascript" src="external.js"></script>
    </head>
    <body>
        <table>
            <tr>
                <td id = "try1" style="background-color:green;"><p id="ChosenColor3"> htmlfile</p></td>
            </tr>
            <tr>
                <td id = "try2"><p id="ChosenColor4"> css file</p></td>
                <td><button id="bestRated3" onclick = arrayTest()> ב.מ </button></td>
                <td><button id="submitForm" onclick = submit()> end</button></td>
            </tr>
            <tr>
                <td><h1 id="ChosenColor5"> text </h1></td>  
            </tr>
        </table>
    </body>
    <script>
        window.onload=aaa();
        function aaa()
        {
            var x = document.getElementById("try2");
            alert(x.style.background);
        }
    </script>     
</html>

As you can see, the message I get is empty. If I will change the ID to "try1" it will be displayed.

like image 957
Doron Cohen Avatar asked Dec 20 '22 00:12

Doron Cohen


1 Answers

The style property lets you read and write the value for each element's style HTML attribute (what is called its inline style) -- it does not take stylesheets into account.

To discover what the real value of a CSS attribute is you have to use window.getComputedStyle instead, for example:

alert(getComputedStyle(x, null).getPropertyValue("background-color"));

See it in action.

Please note that getComputedStyle is not supported by IE 8 or earlier.

like image 118
Jon Avatar answered Jan 08 '23 01:01

Jon