user3852152 user3852152 - 2 months ago 5
CSS Question

jQuery - each element and this each children get and set hight

I know that they here related topics and better way is use flexbox. But how can I make something like this?


  • Find each direct children of each .grid element

  • Find highest element and set it its siblings



Lets say that I have this html

<div class="grid">
<div class="col-3">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia saepe veritatis, veniam! Quisquam quis tenetur eius, debitis possimus expedita eligendi amet incidunt quo. Alias dolores, amet error aperiam, quaerat cumque.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consectetur provident consequatur, id corrupti, vitae, sapiente, ipsa explicabo ad eaque impedit alias vel. Explicabo esse odit, autem ab eius rerum odio.
</div>
<div class="col-2">
short
</div>
</div>

<div class="grid">
<div class="col-3">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia saepe veritatis, veniam! Quisquam quis tenetur eius, debitis possimus expedita eligendi amet incidunt quo. Alias dolores, amet error aperiam, quaerat cumque.
</div>
<div class="col-2">
short
</div>
</div>


And little bit css:

.grid:after {
content: "";
display: table;
clear: both;
}

[class*='col-'] {
float: left;
border: 1px solid black;
}

.col-3 {
width: 30%;
}
.col-4 {
width: 40%;
}
.col-2 {
widdth: 20%;
}


The goal is in first grid set .col-2 same height as .col-3 has and for second .grid do the same.

Here is my jQuery yet:

$(".grid").each(function(){
$(this).children().each(function() {
var height = $(this).height();
console.log(height);
});
});


Codepen is here: http://codepen.io/anon/pen/amzkqy?editors=1011

Answer

Try this:

var max = 0;
$(".grid").each(function(){
  var children = $(this).children();
  children.each(function() {
    if (max < $(this).height()) max = $(this).height();
  });
  children.each(function() {
    console.log(max);
    $(this).height(max);
  })
});

It gets the largest height from the children then sets the height to the maximum.

Comments