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.
9 Respuestas
+ 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') ^^
+ 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) ^^
+ 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...
+ 3
does document.body.scrollHeight work for you?
+ 3
use percentage or viewport values like 60% or 60vh
0
@cheeze Thank you works perfectly. Is there a way of getting it in CSS ?
0
viewport work👍
0
@visph why don't we just use parseInt(s.width)?
0
what if you have 'px' at the end? Will parseInt() work?