Untitled

How to find the width of a div using vanilla JavaScript?

Possible duplicate of Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively (which, indeed, has been asked much later, but still has a much more elaborate answer).

8 Answers 8

document.getElementById("mydiv").offsetWidth 

When myDiv had no CSS rule but had «width» and «height» defined in the tag, offsetWidth returned the parent width. Not a problem I just added the CSS rule and it worked fine.

@nim if your div has display: none or is not part of the document, it will always have zero offset height.

This answer has a detailed visual explanation of the difference between offsetWidth and clientWidth .

You can use clientWidth or offsetWidth Mozilla developer network reference

document.getElementById("yourDiv").clientWidth; // returns number, like 728 
document.getElementById("yourDiv").offsetWidth; // 728 + borders width 

All Answers are right, but i still want to give some other alternatives that may work.

If you are looking for the assigned width (ignoring padding, margin and so on) you could use.

getComputedStyle(element).width; //returns value in px like "727.7px" 

getComputedStyle allows you to access all styles of that elements. For example: padding, paddingLeft, margin, border-top-left-radius and so on.

Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element’s display is ‘none’.

var elem = document.getElementById("myDiv"); if(elem)

You can also search the DOM using ClassName. For example:

document.getElementsByClassName("myDiv") 

This will return an array. If there is one particular property you are interested in. For example:

var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth; 

divWidth will now be equal to the the width of the first element in your div array.

Actually, you don’t have to use document.getElementById(«mydiv») .
You can simply use the id of the div, like:

var w = mydiv.clientWidth;
or
var w = mydiv.offsetWidth;
etc.

The correct way of getting computed style is waiting till page is rendered. It can be done in the following manner. Pay attention to timeout on getting auto values.

function getStyleInfo() < setTimeout(function() < const style = window.getComputedStyle(document.getElementById('__root__')); if (style.height == 'auto') < getStyleInfo(); >// IF we got here we can do actual business logic staff console.log(style.height, style.width); >, 100); >; window.onload=function() < getStyleInfo(); >; 

you can get auto values for width and height because browsers does not render till full load is performed.

Читайте также:  Html тег onclick if

Источник

Setting DIV width and height in JavaScript

I have a div with id=»div_register» . I want to set its width dynamically in JavaScript. I am using this following code:

getElementById('div_register').style.width=500; 

but this line of code isn’t working. I also tried using the units px like the following, still no luck:

getElementById('div_register').style.width='500px'; 
getElementById('div_register').style.width='500'; 
getElementById('div_register').style.width=500px; 

but none of this code is working for me. I don’t know what’s going wrong. I am using Mozilla Firefox. EDIT

    .white_content  
welcome

Did you check, that div_register is the right id of your element? Maybe give us some html, too. style.width=»500px»; should be right.

i have set document.getElementById(‘div_register’).style.display=’block’, and then set document.getElementById(‘div_regsiter’).style.width=’500px’;

For what its worth, you have typos in the word «document» in lines 3 & 4 of your function. which would most definitely keep it from working.

7 Answers 7

The properties you’re using may not work in Firefox, Chrome, and other non-IE browsers. To make this work in all browsers, I also suggest adding the following:

document.getElementById('div_register').setAttribute("style","width:500px"); 

For cross-compatibility, you will still need to use the property. Order may also matter. For instance, in my code, when setting style properties with JavaScript, I set the style attribute first, then I set the properties:

document.getElementById("mydiv").setAttribute("style","display:block;cursor:pointer;cursor:hand;"); document.getElementById("mydiv").style.display = "block"; document.getElementById("mydiv").style.cursor = "hand"; 

Thus, the most cross-browser compatible example for you would be:

document.getElementById('div_register').setAttribute("style","display:block;width:500px"); document.getElementById('div_register').style.width='500px'; 

I also want to point out that a much easier method of managing styles is to use a CSS class selector and put your styles in external CSS files. Not only will your code be much more maintainable, but you’ll actually make friends with your Web designers!

document.getElementById("div_register").setAttribute("class","wide"); .wide < display:block; width:500px; >.hide < display:none; >.narrow

Now, I can easily just add and remove a class attribute, one single property, instead of calling multiple properties. In addition, when your Web designer wants to change the definition of what it means to be wide, he or she does not need to go poking around in your beautifully maintained JavaScript code. Your JavaScript code remains untouched, yet the theme of your application can be easily customized.

Читайте также:  Set mail function in php ini

This technique follows the rule of separating your content (HTML) from your behavior (JavaScript), and your presentation (CSS).

Источник

How to get document height and width without using jquery

How to get document height and width in pure javascript i.e without using jquery.
I know about $(document).height() and $(document).width() , but I want to do this in javascript. I meant page’s height and width.

11 Answers 11

var height = document.body.clientHeight; var width = document.body.clientWidth; 

Check: this article for better explanation.

If a website has a border it takes that off the width with this solution but not the jQuery solution. Unlikely to be a border on the body but worth knowing. window.innerWidth solves this

This returns the height of the browser window (if you adjust the height of the browser it changes), not the height of the content/webpage.

Even the last example given on http://www.howtocreate.co.uk/tutorials/javascript/browserwindow is not working on Quirks mode. Easier to find than I thought, this seems to be the solution(extracted from latest jquery code):

Math.max( document.documentElement["clientWidth"], document.body["scrollWidth"], document.documentElement["scrollWidth"], document.body["offsetWidth"], document.documentElement["offsetWidth"] ); 

just replace Width for «Height» to get Height.

problem with clientWidth is it is viewable only. scrollWidth includes things leaking off the screen. at least, this is true for my Chrome experiments in 2019.

@StayCool it seems that the most recent jQuery is still using this method for the document height/width calculation and it gives the same result as $(document).width() . Maybe you are after something like $(window).width() which in pure JS would be just document.documentElement[«clientWidth»] on modern browsers.

This is a cross-browser solution:

var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; 

You should use getBoundingClientRect as it usually works cross browser and gives you sub-pixel precision on the bounds rectangle.

elem.getBoundingClientRect() 

Probably because your body has height 0. If you don’t change its display type that’s the case by default. Check it in the DOM inspector.

Get document size without jQuery

document.documentElement.clientWidth document.documentElement.clientHeight 

And use this if you need Screen size

document.body.offsetHeight document.body.offsetWidth 

Be careful of using these in things like window resize events. they have to calculate the height & width, which takes a while.

Читайте также:  Коды для рекламы в css

This should work for all browsers/devices:

If you want to get the full width of the page, including overflow, use document.body.scrollWidth .

window is the whole browser’s application window. document is the webpage shown that is actually loaded.

window.innerWidth and window.innerHeight will take scrollbars into account which may not be what you want.

document.documentElement is the full webpage without the top scrollbar. document.documentElement.clientWidth returns document width size without y scrollbar. document.documentElement.clientHeight returns document height size without x scrollbar.

Источник

Get content width of an element

offsetWidth isn’t good enough for me right now, as this includes padding and border width. I want to find out the content width of the element. Is there a property for that, or do I have to take the offsetWidth and then subtract the padding and border width from the computed style?

4 Answers 4

Since this comes up first when googling but doesn’t have an appropriate answer yet, here’s one:

function getContentWidth (element)

Basically, we first get the element’s width including the padding ( clientWidth ) and then substract the padding left and right. We need to parseFloat the paddings because they come as px -suffixed strings.

I’ve created a little playground for this on CodePen, check it out!

It sounds to me like you want to use getComputedStyle on the element. You can see an example of getComputedStyle vs. offsetWidth here: http://jsbin.com/avedut/2/edit

window.getComputedStyle(document.getElementById('your-element')).width; 

That would have been an important bit to include from the start. 😉 And in that case, yes: I think you need to do some subtraction. I’ve added a getWidth to the jsbin: jsbin.com/avedut/6/edit (and the way it was phrased there at the end tripped me up a little, sorry)

I would suggest either scrollWidth or the clientWidth depending on whether you want to account for the scrollbar.

I have the similar issue where my parent element isn’t the window or document. I am loading an image by Javascript and want it to center after loading.

var parent = document.getElementById('yourparentid'); var image = document.getElementById('yourimageid'); image.addEventListener('load'),function() < parent.scrollBy((image.width-parent.clientWidth)/2,(image.height-parent.clientHeight)/2); >

Whenever you set the src then it will scroll to the center of the image. This for me is in the context of zooming into a high res version of the image.

Источник

Оцените статью