Me hdi
Me hdi

Reputation: 1912

How get element width by javascript

what's the JavaScript code for the find the 's width?

(I want get width .FixedBox whit javascript no jquery, but my code don't work.)

alert(document.getElementsByClassName('FixedBox').offsetWidth);
<div class="FixedBox">
    The HTMLElement.offsetWidth read-only property returns the layout width of an element. Typically, an element's offsetWidth is a measurement which includes the element borders, the element horizontal padding, the element vertical scrollbar (if present, if rendered) and the element CSS width.
</div>

Upvotes: 0

Views: 3540

Answers (3)

Ansh Takalkar
Ansh Takalkar

Reputation: 119

Try This

document.getElementsByClassName('FixedBox')[0].offsetHeight

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115202

The Document.getElementsByClassName() returns NodeList you need to get element from collection to get offsetWidth property. Also put them inside window load callback to execute only after elements are loaded.

window.onload = function() {
  var ele = document.getElementsByClassName('FixedBox');
  alert(ele.length ? ele[0].offsetWidth : 'no elements with the class');
}
<div class="FixedBox">
  The HTMLElement.offsetWidth read-only property returns the layout width of an element. Typically, an element's offsetWidth is a measurement which includes the element borders, the element horizontal padding, the element vertical scrollbar (if present,
  if rendered) and the element CSS width.
</div>

Upvotes: 2

wot
wot

Reputation: 845

This might work

$('.FixedBox').load(function () {
    alert(document.getElementsByClassName('FixedBox')[0].getBoundingClientRect().width)
});

alert(document.getElementsByClassName('FixedBox')[0].getBoundingClientRect().width)
<div class="FixedBox">
  The HTMLElement.offsetWidth read-only property returns the layout width of an element. Typically, an element's offsetWidth is a measurement which includes the element borders, the element horizontal padding, the element vertical scrollbar (if present,
  if rendered) and the element CSS width.
</div>

Upvotes: 0

Related Questions