Adjust height of divs to height of tallest
by Megi93
HTML
<h2>Build a javascript function that takes a class name, finds all divs that contain that class name, and sets their height to equal the height of the tallest div</h2>
<h3>Before</h3>
<div class="group">
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
</div>
<h3>After</h3>
<div class="group">
<div class="a equal"></div>
<div class="b equal"></div>
<div class="c equal"></div>
</div>
CSS
.group:after {
content: "";
display: table;
clear: both;
}
.a,
.b,
.c {
background-color: red;
float: left;
margin-left: 20px;
width: 100px;
}
.a {
height: 200px
}
.b {
height: 300px;
}
.c {
height: 150px;
}
JavaScript
function equalHeights(className) {
var div = document.getElementsByTagName("div");
var tallest = 0;
// Loop over matching divs
for (i = 0; i < div.length; i++) {
var ele = div[i];
var eleHeight = ele.offsetHeight;
tallest = (eleHeight > tallest ? eleHeight : tallest); /* look up ternary operator if you dont know what this is */
}
var findClass = document.getElementsByClassName(className);
for (i = 0; i < findClass.length; i++) {
findClass[i].style.height = tallest + "px";
}
}
equalHeights('equal');