Reputation: 3058
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?
Upvotes: 10
Views: 7530
Reputation: 187040
Since display is not set directly as a style property, you won't get that using the above code. You have to get the computed value.
You can refer this page, Get styles
To get the value
var displayValue = getStyle("test", "display");
function getStyle(el,styleProp)
{
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
Upvotes: 3
Reputation: 5993
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>
Upvotes: 6
Reputation: 17977
The CSS won't be loaded yet. Wrap your JavaScript in an "on-ready" event.
<body onload="alert(document.getElementById('test').style.display);">
Does that work for you?
Upvotes: 0