Reputation: 35
I know this properbly is a duplicate, but i cant get it right from some of the other answers! Really hope you can help!
I simply want to get the width of an element, and then assign it to the height of the same element.
But i cant seem to get the width passed... And I really dont know why - just gets and "undefined".
Read something about the js asking for the width before the elements are added to the DOM, but no matter where I place my "onload", og place the js script, it doesnt seem to make any difference, and i still can add static height to the same element, but just cant get the width! Thanks!
var width_ele = document.getElementsByClassName("image");
var width = width_ele[0].style.offsetWidth;
alert(width);
var ele = document.getElementsByClassName("image");
for (var i = 0; i < ele.length; i++) {
ele[i].style.height = 100 + "px"; // here I wanted the "100" to be the variable "width"...
}
http://jsfiddle.net/qL0hj4jc/10/
Upvotes: 1
Views: 7917
Reputation: 28445
I have updated your code.
You need to use
var width = width_ele[0].offsetWidth;
Here is the updated fiddle - http://jsfiddle.net/qL0hj4jc/4/
You should use the .offsetWidth and .offsetHeight properties. Note they belong to the element, not .style.
Upvotes: 3
Reputation: 33399
var width = width_ele[0].offsetHeight; // did you mean offsetWidth?
offsetHeight
/offsetWidth
is a property of the element itself, not its style table.
Upvotes: 4