April 9, 2013

Append without last element

Joesandeek’s Questions:

<div id="container">
    <div class="sub">a</div>

    <span id="add">add</span>
</div>            

$('#add').click(function(){
   $('#container').append('<div class="sub">a</div>');
})

This append element to #container on bottom. How can i add this element on bottom without last element(#add)? I would like have always #add on bottom.

Fiddle: http://jsfiddle.net/nk67d/

Try

$("#add").prepend('<div class="sub">a</div>');

See fiddle: http://jsfiddle.net/nk67d/1/

Use .before(), it adds the markup before the matched elements.

$('#add').before('<div class="sub">a</div>');

To complete the answer:

$('#add').click(function(){
   $(this).before('<div class="sub">a</div>');
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!