Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use javascript to get the style of an element from an external css file

I have a html like this:

<html>
    <head>
        <link rel="stylesheet" type="text/css" media="all" href="style.css">
    </head>

    <body>
        <div id="test">Testing</div>

        <script>
            alert(document.getElementById('test').style.display);
        </script>
    </body>
</html>

The style.css:

div {
    display:none;
}

I expect the js would return "none", but it return an empty string instead. Is there any way to solve this problem?

like image 210
Alan Avatar asked Apr 01 '10 04:04

Alan


People also ask

How do I link external CSS to JavaScript?

To link a CSS file with your HTML file, you have to write the next script on your HTML file inside the head tag. To link a Js file with your HTML, you only have to add the source of the script inside the body tag or outside; it doesn't matter.

How do I get CSS style of an element?

The CSS of an element can be obtained using the getComputedStyle element function in JavaScript. It returns a JavaScript object containing CSS properties and their values. This object is indexed and iterable over the property names. The getPropertyValue(property) is used to get the value of a property.

How do you reference an external CSS file?

External CSS Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section.

How do you access styles in JavaScript?

First, you need to select the element with querySelector . Then, you use getComputedStyle to get the element's styles. If you log style , you should see an object that contains every CSS property and their respective values. You can also see this object in Chrome's and Firefox's dev tools.


1 Answers

This would work for standards compliant browsers (not IE - currentStyle/runtimeStyle).

<body>
    <div id="test">Testing</div>

    <script type="text/javascript">
        window.onload = function() {
            alert(window.getComputedStyle(document.getElementById('test'),null).getPropertyValue('display'));
        }
    </script>
</body>

like image 176
Jonathan Avatar answered Oct 06 '22 01:10

Jonathan