Denis
Denis

Reputation: 3759

Get real element's width in JavaScript

For example, I have the next HTML markup (imitating my custom dropdown list inside a generic div):

$(document).ready(function() {
    $("#selectbox-body").css("width", $("#selectbox").width());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div id="outer-div">
	<label style="float: left; width: 100px; background-color: blue">LABEL</label>
	<div id="selectbox" style="background-color: pink">......</div>
	<div id="selectbox-body" style="position: absolute; height: 100px; background-color: red">12312313</div>
</div>

Or http://jsfiddle.net/sdkpkLds/ .

#selectbox.width equals to #outer-div.width, not #outer-div.width - label.width. How can I place #selectbox-body not under label?

Upvotes: 0

Views: 1551

Answers (1)

To get the real, currently computed dimensions, you have two options:

  1. getComputedStyle(element,null).getPropertyValue("width")
  2. element.getBoundingClientRect().width

The first is a CSS string with (px) unit, the second is a number.

(asking for the supposed CSS rule will only get you the "this is what the stylesheet/inline style says" information, which is very different from asking for the actual computed current dimensions)

Also note that getComputedStyle is a global function. Old tutorials might tell you to use document.getDefaultView.getComputedStyle or the like, which is no longer necessary.

Upvotes: 2

Related Questions