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?
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.
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.
External CSS Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With