How can I get the properties of an element with jquery? I want to get the size of the margin of a div in particular.
I have set the style of the div in a .css file, for instance,
.item-form {
margin:0px 0px 10px 0px;
background: blue;
}
the html,
<form>
...
<div class="item-form">
<textarea class="autohide"></textarea>
</div>
...
</form>
I tried with this code, but it fails obviously,
$(".autohide").each(function(){
var $this = $(this);
alert($this.parents("div:.item-form").css("margin"));
});
any ideas? thanks.
You'll want to use...
alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));
From jQuery's website
Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.
Exemple, for :
<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>
In this js code :
var myMarginTop = $("#myBlock").css("marginBottom");
The var becomes "15px", a string.
If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.
The fastest is to use native js method :
var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );
Source: Stackoverflow.com