0

I am trying to get display attribute about an element using style.display. But its not returning anything. Have a look at the JsFiddle one.

http://jsfiddle.net/4v5LS/1/

There is nothing in the alert window.

UPDATE

Now I just noticed something unusual. Whenever I define the properties inline then things do work. But when I apply style in any other method, then its not working.

user2040026
  • 178
  • 7
  • The *style.display* property returns values set directly on the element, not inherited (or computed) values. – RobG Jun 06 '14 at 11:00
  • But the `box` div is not inside any other div. And I specified the `display` in the CSS. So what is to be computed here ? I am not getting a grasp on this fact. – user2040026 Jun 06 '14 at 11:11
  • Element styling is computed based on styles directly on the element, those inherited from parent elements and those calculated from CSS. The style object only holds values for properties set directly on the element. All the rest (including those from CSS) are computed. Have a look at the marked duplicate. – RobG Jun 06 '14 at 13:01
  • Oh. Okay. I got it now. Thanks a lot. It was very very helpful. – user2040026 Jun 06 '14 at 13:33

1 Answers1

1

You can use getComputedStyle()

document.getElementById('button').onclick = function() {
     element = document.getElementById('box');
     style = window.getComputedStyle(element),
     display = style.getPropertyValue('display');
    alert(display);
}

fiddle

Alex Char
  • 32,879
  • 9
  • 49
  • 70
  • 1
    Please don't post code–only answers. Explain what the OP did wrong and why your answer "works". – RobG Jun 06 '14 at 11:00
  • Everytime i tried to do this always other users post answers faster than me and i spended my time to answer to OP for nothing ;) – Alex Char Jun 06 '14 at 11:04
  • There is nothing to stop you from editing your answer to add more detail. – RobG Jun 06 '14 at 11:11
  • I posted my answer and after 15 secs(sorry can't remember exacly) you downvote me for that reason. Didn't have time to react :). Another time when i posted my answer and after i started edit it to explain why i posted the code another user blamed me that i edit my first post and this is not right :/ anyway Thx @RobG i will follow your advice in future :) – Alex Char Jun 06 '14 at 11:18
  • I didn't down vote you. If you edit your post, whoever did can remove the down vote (if they come back…). – RobG Jun 06 '14 at 12:59