0

How do I get the CSS property top from a element in javascript.

I have tried document.getElementById(element).offsetTop however this always returns 0. When I have set top: 500px; in the CSS of element.

1
  • google for currentStyle.top and getComputedStyle(). Commented Nov 12, 2009 at 11:53

3 Answers 3

5

offsetTop gets the position of the element on the page (relative to an offsetParent, which is any positioned element or occasionally some other types of element) in pixels as a Number.

style.top gets the String value of the top property in style="top: 500px" inline attributes only.

If you want to get a top style value that has been set from a stylesheet, you can't use style.top which will just return '' to tell you top hasn't been set in the style attribute. Instead there is window.getComputedStyle which is defined by DOM Level 2 Style, and element.currentStyle which is used by IE. (Older browsers won't support either.)

var top= (window.getComputedStyle?
    window.getComputedStyle(element, null).getPropertyValue('top') :
    element.currentStyle? element.currentStyle.top : '0'
);

There are usually better ways around that don't involve trying to read stylesheets.

Sign up to request clarification or add additional context in comments.

Comments

0

offsetTop returns the top offset to the node lower in the tree that has position:relative; or position:absolute; set.

Do you have the parent's position set to relative or absolute?

Comments

-1

Try

element.style.top 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.