# How To Calculate Each Child Div Height And Width

## 13 January 2020 - 1 answer

How calculate height and width of child DIVs.

I want to calculate height and width of each child DIV then compare its width and height. If Width is greater then Height then add class1 or height is greater then width then add class2. And width is equal to height then add class3

``````\$(window).load(function() {
\$('.grid').children().each(function(item) {
var divHeight = 0;
var divWidth = 0;
divHeight = \$('.grid-item').height();
divWidth = \$('.grid-item').width();
console.log(divWidth);
console.log(divHeight);
//check if child div's width is greater then height then add some class
if (\$(this).width() > \$(this).height()) {
if (\$(this).hasClass('class1')) {
\$(this).removeClass('class1');
} else {
}
}
});
});``````
``````* {
box-sizing: border-box;
}

body {
font-family: sans-serif;
}

/* ---- grid ---- */

h1 {
text-align: center
}

.grid {
background: #DDD;
max-width: 1200px;
margin: 0 auto;
}``````
``````<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Isotope - masonry layout mode</h1>
<div class="grid">
<div class="grid-item">
<img src="https://via.placeholder.com/300/09f/fff.png" alt="">
</div>
<div class="grid-item">
<img src="https://via.placeholder.com/728x90.png" alt="">
</div>
<div class="grid-item">
<img src="https://via.placeholder.com/500x100.png" alt="">
</div>
</div>``````

if children of `class="grid"` is always `class="grid-item"` better use selector as `\$('.grid-item')`

• also use `.outerHeight()` and `.outerWidth()` method to calculate the exact height and width with margins

``````\$('.grid-item').each(function() {
let \$this = \$(this);
let divHeight = parseFloat(\$this.outerHeight());
let divWidth = parseFloat(\$this.outerWidth());
let className = "";
//check if child div's width is greater then height then add some class
className = divWidth > divHeight ? 'class1' : 'class2';
if (divWidth === divHeight)
className = 'class3';
});``````
``````* {
box-sizing: border-box;
}

body {
font-family: sans-serif;
}

/* ---- grid ---- */

h1 {
text-align: center
}

.grid {
background: #DDD;
max-width: 1200px;
margin: 0 auto;
}
.class1 { background-color: red; }
.class2 { background-color: blue; }
.class3 { background-color: yellow; }``````
``````<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Isotope - masonry layout mode</h1>
<div class="grid" >
<div class="grid-item" style="height:200px;width:200px;" >
<img src="https://via.placeholder.com/300/09f/fff.png" alt="">
</div>
<div class="grid-item">
<img src="https://via.placeholder.com/728x90.png" alt="">
</div>
<div class="grid-item" style="height:203px;width:201px;">
<img src="https://via.placeholder.com/100x500.png" alt="">
</div>
</div>``````