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 开发者_StackOverflow中文版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);
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.
$('<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());
}):;
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.
精彩评论