In general, these things are better done on css. There are different ways and to understand what to apply in your case, you need to know the whole task.
As for your code, there is a lot that is not true in it.
document.getElementsByClassName('.box');
This selector does not work that way. The point here is not needed document.getElementsByClassName ('box')
height = 0;
The variable will be reset on each iteration of the loop. It must be taken out of the cycle.
this
This is a keyword and in this case it refers to a global object. If you use such a loop, then you can refer to the element like boxes[i]
You do not change the height of the blocks anywhere
Since you want, you can do so:
var boxes = document.getElementsByClassName('box'); var height = 0; //Определяем максимальную высоту блока for( var i = 0; i < boxes.length; i++ ){ var current_height = boxes[i].offsetHeight; if(current_height > height) { height = current_height; } } //Задаем максимальную высоту блока всем элементам for( var i = 0; i < boxes.length; i++ ){ boxes[i].style.height = height + 'px'; }
.box { width: 50px; background-color: blue; margin: 10px; } .box1 { height: 40px } .box2 { height: 30px } .box3 { height: 70px }
<div class="box box1"></div> <div class="box box2"></div> <div class="box box3"></div>
var height = 0;
declare before the loop, not in the loop. - Dmitriy Kondratiuk