3

I use .outerHeight to set the height of another div, using a class as selector.

var $example = $('.example');
var $height = $example.outerHeight();
var $styles = { 'height': $height }
$('.wrapper_sub').css($styles);

I want to use this on multiple "slides" of my site:

<div class="wrapper">
  <div class="example">Some Content</div>
  <div class="wrapper_sub">Other Content</div>
</div>
<div class="wrapper">
  <div class="example">Some Content</div>
  <div class="wrapper_sub">Other Content</div>
</div>
<div class="wrapper">
  <div class="example">Some Content</div>
  <div class="wrapper_sub">Other Content</div>
</div>

How can I get the .outerHeight of every .example, take only the highest value and append this to all .wrapper_sub divs?

Tushar
  • 85,780
  • 21
  • 159
  • 179
Marian Rick
  • 3,350
  • 4
  • 31
  • 67

2 Answers2

1

Loop through the .example elements and get the max value. Then apply this value to those elements:

//Set an empty array
var arr = [];

//Loop through the elements
$('.example').each(function() {
   //Push each value into the array
   arr.push(parseFloat($(this).outerHeight()));
});

//Get the max value with sort function
var maxH = arr.sort(function(a,b) { return b-a })[0];

//Apply the max value to the '.example' elements
$('.example').css({'height': maxH + 'px'});
kapantzak
  • 11,610
  • 4
  • 39
  • 61
1

See comments inline:

var maxHeight = 0; // Initialize to zero
var $example = $('.example'); // Cache to improve performance

$example.each(function() { // Loop over all the elements having class example

    // Get the max height of elements and save in maxHeight variable
    maxHeight = parseFloat($(this).outerHeight()) > maxHeight ? parseFloat($(this).outerHeight()) : maxHeight;
});

$('.wrapper_sub').height(maxHeight); // Set max height to all example elements

DEMO

Marian Rick
  • 3,350
  • 4
  • 31
  • 67
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Am I able to use a variable to improve the performance for `.example`, or does this cache only one element, and not every class it finds? – Marian Rick Jun 29 '15 at 06:36
  • @MarianRick Thanks! Updated answer – Tushar Jun 29 '15 at 06:38
  • I would love to mark your answer as the correct one, but you need to "correct" it to fit my answer (for the google record). I need to get the max height of `.example` and apply this value to every `.wrapper_sub` on page. – Marian Rick Jun 29 '15 at 06:41
  • @MarianRick Didn't get you – Tushar Jun 29 '15 at 06:42
  • I am able to understand and use your code, thats great. But in my question I do not want to apply the max-height of `.example` to all the other `.example` divs, I want to apply it to the `.wrapper_sub` divs. I have made an edit to your answer to fit as solution to my question! ;) Thanks a lot for your help! – Marian Rick Jun 29 '15 at 06:46
  • @MarianRick Thanks! Glad to help you – Tushar Jun 29 '15 at 06:49