Hello! There is such a repeating fragment of html code:

<div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="clear"></div> </div> 

This structure can be presented in two versions - a table and rows, the corresponding switch is already implemented.

You need to align the item height only for the "table" view, when they are presented as columns and reset to auto when switching to the "row" mode, so that each item has its own height (otherwise there will be extra padding between the lines).
Those. each div with the item class must be set to the maximum of their heights in the current row block.
It is desirable through jQuery ... But any options are welcome!

I tried this:

  $('.item').height( $('.item').parent().children().filter('.item').height() + 'px' ); 

But this is how the height is set only for the first item , and its own, i.e. nothing changes.

    2 answers 2

     $('div.row').each(function(){ var heights = []; $('.item', this).each(function(){ heights.push($(this).height());// заносим Π² массив высоты всСх Π±Π»ΠΎΠΊΠΎΠ² }); $('.item', this).height(Math.max.apply(null, heights));//Π½Π°Ρ…ΠΎΠ΄ΠΈΠΌ ΠΈ устанавливаСм этот максимум }); 

    UPD: updated answer

    • one
      Thanks, it seems the principle is understood ... Slightly changed your code: $ ('. Item'). Each (function () {var h = Math.max.apply (Math, $ (this) .parent (). Map (function () {return $ (this) .height ();}). get ()); $ (this) .height (h + 'px');}); - t1nk
    • 2
      o.height(h + 'px'); such a record is redundant, you can not add the line 'px', and why should you go through all the elements, then contact each time their parent ... and then I got confused - Specter
    • I need to find the maximum height of not all divs with the item class, but only among those that belong to the same div with the class row and assign them this maximum height. - t1nk
    • one
      then change the selector to "div.row > .item" - Specter
    • I have not met with such a selector, thanks - I will study. - t1nk
     $.fn.equalizeHeights = function() { var maxHeight = this.map(function(i,e) { return $(e).height(); }).get(); return this.height( Math.max.apply(this, maxHeight) ); }; 

    Using:

     $('.item').equalizeHeights(); 

    Less costly than bypassing using $.each

    • 3
      > Less expensive in terms of resources than crawling with $ .each on your map magically makes less iterations? - Specter
    • one
      Thanks, markuper , a good example. I'll take a note. Specter , i.e. Are you saying that map and each are equal in speed? - t1nk
    • 2
      they are based on loops with the same number of iterations - Specter
    • one
      This example is given in the API of JKveri himself, jointly with the MEP method, therefore I think that using mep in this case is more reasonable than each - markuper
    • those. Do you admit that "less expensive in terms of resources" are empty words? - Specter