Search code examples
jquerycssdynamic-sizing

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


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);

Solution

  • 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.