I am a beginner coder. It is probably very simple, but I tried to find the answer and have not succeeded. My question is why do width
and height
properties of div
object return undefined
while they are apparently 100px both?
In this topic is explained how to get .offsetWidth
property. But as I understand it is not 100% the same as .width
.
window.onload = function() {
var test = document.getElementById("test");
test.addEventListener("click", select);
function select(e) {
var elementID = e.target.id;
var element = document.getElementById(elementID);
var width = element.width;
console.log(element);
console.log(width);
}
}
div#test {
position: absolute;
height: 100px;
width: 100px;
background-color: black;
}
<div id="test"></div>
My answer
Thank you all guys for your answers. They pushed me to find my own simple solution which I hope will be helpful for such beginners as me. The answer is: div
DOM object does not have .width
and .height
property even if you assign them in CSS and they work well. For this purpose it has .style.width
and .style.height
respectively. But even if you assign them through CSS they will not appear in element.style
until you do it purposefully using Java Script. So to get width
or height
of the div
element through JS first of all remove these properties from CSS. You will not need them anymore. Then assign width
through element.style.width
command and then you can easily get it whenever you want using element.style.width
.
CSS
div {
position: absolute;
background-color: black;
}
JavaScript
window.onload = function() {
var test = document.getElementById("test");
test.addEventListener("click", select);
test.style.width = "100px";
test.style.height = "100px";
function select(e) {
var elementID = e.target.id;
var element = document.getElementById(elementID);
var width = element.style.width;
console.log(element);
console.log(width);
}
}