jQuery dynamically change height of element according to the height of another

3k Views Asked by At

I know this question has been answered but I still need help for my specific situation

I have

<ul>
<li>blah blah</li>
<li>blah blah blah</li>
</ul>

I have managed to insert a div after each li using

$('<div class="shadow-hide"></div>') .appendTo('div#main nav.left ul li');

So the html is now

<ul>
  <li>blah blah</li>
  <div class='shadow-hide'></div>
  <li>blah blah blah</li>
  <div class='shadow-hide'></div>
</ul>

but how do I set the height of the div to match the height of the li before it?

here's my attempt so far but I guess it just gets the height of the first li:

$('<div class="shadow-hide"></div>') .appendTo('div#main nav.left ul li');
    var liHeight = $("div#main nav.left ul li").height();
    $('div.shadow-hide').css('height', liHeight);
3

There are 3 best solutions below

2
On BEST ANSWER

perhaps:

$('.shadow-hide').height(function() {
   return $(this).prev('li').height();
});

or perhaps more in line with your actual use case:

$('#main nav.left ul li').each(function(i, el) {
  var $el = $(el), height = $el.height();
  $('<div class="shadow-hide" />').height(height).appendTo($el);
});

Edit: as noted in the comments, you can't nest a div directly in a list, so you might want to rethink however you're styling this, perhaps replacing the "shadow-hide" divs with list items.

1
On

$('<div class="shadow-hide"></div>') .appendTo('div#main nav.left ul li'); this line is going to append the div inside each of the li's. But the markup which you have shown is wrong, div should go inside each li.

Now you can try the below script to set the height of shadow-hide divs within each li.

$("div#main nav.left ul li").each(function(){
   $(this).find(".shadow-hide").height($(this).height());
}):;
0
On

Both can be done concisely and efficiently using .append(function(index, html), which I think makes more sense in this scenario:

var div = '<div class="shadow-hide">Test</div>';

$("ul li").append(function(index, html) {
    return html + ($(div).height($(this).height()).html());
});

Demo.