简体   繁体   中英

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> 

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> 

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> 

尝试这个

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM