Reputation: 79299
For some reason I can't access HTML element's display
style's value.
Here's my JavaScript code:
var el = document.querySelector('#warning');
console.log(el.style.display)
My code returns ""
empty string for #warning
's display
style but it's actually "none"
.
I've the following HTML:
<div id="warning">
warning warning warning.
</div>
I've the following CSS:
#warning {
display: none;
}
Any ideas?
Upvotes: 0
Views: 620
Reputation: 14530
If you know the element is an ID I'd suggest you use the getElementById();
function. Also AFAIK the style method gets inline styles only. I'd suggest using getComputedStyle();
.
Code
var myDiv = document.getElementById("myDiv");
alert(getComputedStyle(myDiv).display);
Will output "none".
Example
Reading Material
Not directly related to your question but the answer has some good points.
Upvotes: 1
Reputation: 2830
You are doing everything right for the most part, but what you are running into is a hangup for most people when they try this for the first time.
The style object in javascript is looking for this value to be inside the actual element (inline) and does not look for it in css code directly.
To access the style, the style has to exist in the dom. You could look into Window.getComputedStyle()
I hope this explains why you are reaching this roadblock.
Upvotes: 1