agon024 agon024 - 17 days ago 6
Javascript Question

jQuery - get height of element and apply that height to another element inside same parent

Here is a fiddle - https://jsfiddle.net/t6tpxqco/18/

What I am trying to do is grab height of an element ".right" and apply an inline style to ".left" that matches the height of the .right grabbed by jQuery:

<li class="first">
<div class="left"></div>
<div class="right">
<h1>Bear claw bear claw biscuit biscuit.</h1>
<p class="nfo">Bear claw bear claw biscuit biscuit bonbon candy canes chocolate chocolate cake gingerbread. Gummies chocolate bar dragée tootsie roll. Chocolate bar sweet roll oat cake bear claw dragée chocolate bar chocolate bar.</p>
<a href="" class="readMore">Read More</a>
</div>
</li>

<li class="second">
<div class="left"></div>
<div class="right">
<h1>Chocolate bar sweet roll oat cake bear claw dragée</h1>
<p class="nfo">Bear claw bear claw biscuit biscuit bonbon candy canes chocolate chocolate cake gingerbread. Gummies chocolate bar dragée tootsie roll. Chocolate bar sweet roll oat cake bear claw dragée chocolate bar chocolate bar.Pudding chupa chups soufflé sweet roll jelly jujubes cake chocolate cake. Tiramisu gummies pastry donut caramels. Tart pastry liquorice tiramisu.</p>
<a href="" class="readMore">Read More</a>
</div>
</li>


Here is the jQuery code I'm using:

var pressHeight = $('.right').height();
$('.left').css({
height: pressHeight
})


So the problem is that it obviously grabs the height of the .right element in the .first list item and applies that height to all of the .left elements.

But if you look at the fiddle, each .right element is a different size than one another. What I need to do is match the .left(picture) element's height with its respective .right element inside the same parent list item.

So to help simplify I need the picture in each list item to match the height of the content to its right.

How can I do this.

NOTE: this is content that is generated through the WordPress loop so I cannot add ID's to the list item.

Answer

Try addressing each element individually:

$('.left').each(function() {
   var $r = $(this).siblings('.right').first();
   var h = $r.height();
   $(this).css({
       height: h
   });
});

What this code does is loops through all .left elements. For each one, it finds a sibling with class .right, by using .siblings('.right'). I included a .first() just to be safe, although I don't expect there to ever be multiple .right siblings.

Comments