Animate div height to fit new content

by Kishore Sahasranaman

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
    row 1<br>
    row 2<br>
    row 3<br>
</div>

CSS

#container {
    border: 1px solid black;
}

JavaScript

var container = $('#container');
container.click(function(e) {
   var element = $(this);
   var height = element.height();
    element.hide();
    element.html(
        'row 1<br>row 2<br>row 3<br>row 4<br>row 5<br>row 6<br>'
    ); // please think of appending the new items alone?
    var height2 = element.height();
    element.css({height : height});
    element.show();
    element.animate( {height : height2} , 500);
});