Read the width of a div using JavaScript

I am trying to read the width of a div without jQuery. The code I'm using is:

JS:

var windowwidth = parseInt(document.getElementById("window").style.width); window.onload = function start() { alert(windowwidth); } 

HTML:

 <div id="window"> <p>Lorem ipsum dolor sit amet.</p> </div> 

CSS

 #window { height: 250px; margin: 0 auto; width: 600px; } 

I don’t understand why this does not work, I looked through this whole site and Google and can not find a solution. I don't want to use jQuery for this (it's a small custom HTML5 script, so I don't need this huge library for one little thing), and even when I try to use the jQuery method, it still doesn't work.

+1
source share
5 answers

You are not guaranteed that document.getElementById() will work (i.e. return the necessary item) until the DOM is ready. So try:

 window.onload = function() { // removed the name to avoid some IE leaks var windowwidth = parseInt(document.getElementById("window").style.width); alert(windowwidth); } 
+2
source

do not read the style property, read the actual width of the element:

 window.onload = function(){ alert(document.getElementById('window').offsetWidth); } 

offsetWidth is what the browser says - it is a width that may differ from what you set with CSS if, for example, the content stretches its width.

+2
source

If you want to see how jQuery does this, here is the link to the source: https://github.com/jquery/jquery/blob/master/src/dimensions.js

+1
source

I would use jQuery to do such a thing. You can find what you need right here: http://api.jquery.com/width/

0
source

You can get style.width only after drawing the element. Try entering the code in setTimeout (). Sometimes it helps me

 window.onload = function(){ setTimeout( function(){ alert(document.getElementById('window').style.width); }, 200 ); } 
0
source

Source: https://habr.com/ru/post/949643/


All Articles