Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get margin value of a div in plain JavaScript?

I can get height in jQuery with

$(item).outerHeight(true); 

but how do I with JS?

I can get the height of the li with

document.getElementById(item).offsetHeight 

but i will always get "" when I try margin-top:

document.getElementById(item).style.marginTop 
like image 403
YuC Avatar asked Jan 11 '13 09:01

YuC


People also ask

How do you find margin value?

To find this, divide your gross profit by revenue. Multiply the total by 100 and voila—you have your margin percentage.

How do you give a margin in Javascript?

Definition and Usage Two values, like: div {margin: 50px 10px} - the top and bottom margins will be 50px, left and right margins will be 10px. Three values, like: div {margin: 50px 10px 20px}- the top margin will be 50px, left and right margin will be 10px, bottom margin will be 20px.

Can a div have margin?

html - Div still has margin even with margin: 0; - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

What is margin in HTML code?

Margin is the space outside of an element. It is the space between an element and the elements around it. If you want an element to be farther away from other elements, increase the margin property.


1 Answers

The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).

To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).

Example:

var p = document.getElementById("target"); var style = p.currentStyle || window.getComputedStyle(p);  display("Current marginTop: " + style.marginTop); 

Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p element in IE9, I get back "1em".

Live Copy | Source

like image 132
T.J. Crowder Avatar answered Sep 23 '22 11:09

T.J. Crowder