0

Get Size of an Element

Is there a built-in function or property to get the size(width and height) of an element? Either with html, css or javascript. If possible I would like to do this with each of the above languages(ie a different way for each language) For example I would like to get the size of the body or the window in order to place things exactly where I want.

8th Jul 2017, 11:15 AM
Mame86
Mame86 - avatar
9 odpowiedzi
+ 5
.scrollHeight is variously implemented in browsers: making it working cross-browser could be a little tricky ^^ Another way of getting calculated css property of any html element is to use the document.getComputedStyle() method, wich return a 'style' object: var e = document.getElementById('myElement'); var s = document.getComputedStyle(e); alert('width: '+s.width); alert('height: '+s.height); However, the values returned are string, witb an explicit unit (px)... So, to use them for calculation you need to cast them to Number: var w = parseInt(s.width); parseInt() and parseFloat() return a number if a valid one start the string (even if there's chat after), while Number() require a valid number in whole string: var h = Number(s.height.substr(0,s.height.length-2); Here, we have used substr() method to retrieve the unit char (that we know is 2 char long -- "px') ^^
8th Jul 2017, 5:38 PM
visph
visph - avatar
+ 4
Following the context, you could use parseInt() if you are sure that the value is integer (or if it doesn't matter to round it)... or parseFloat() if you need a floating point value... as they are easiest to handle with not 'clean' string numbers. But however, Number() object creator advantage is to return an integer or a float depending of the context (return the most suited type) ^^
8th Jul 2017, 6:06 PM
visph
visph - avatar
+ 4
Yes, parseInt() and parseFloat() return a valid number if the string end with not number character, while Number() will return 'NaN' (Not a Number) in such case...
8th Jul 2017, 6:11 PM
visph
visph - avatar
+ 3
does document.body.scrollHeight work for you?
8th Jul 2017, 11:36 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 3
use percentage or viewport values like 60% or 60vh
8th Jul 2017, 11:46 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
0
@cheeze Thank you works perfectly. Is there a way of getting it in CSS ?
8th Jul 2017, 11:43 AM
Mame86
Mame86 - avatar
0
viewport work👍
8th Jul 2017, 11:48 AM
Mame86
Mame86 - avatar
0
@visph why don't we just use parseInt(s.width)?
8th Jul 2017, 5:42 PM
Mame86
Mame86 - avatar
0
what if you have 'px' at the end? Will parseInt() work?
8th Jul 2017, 6:09 PM
Mame86
Mame86 - avatar