Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Prepend before an element

I have a html structure like this/

<li id="1"></li>
<li id="2"></li>
<li id="3"></li>
<li id="comment-box"></li>

now i wanna prepend

<li id="4"></li>

before comment-box.

i am submitting a form from the comment box and once its a success i wanna do the prepend.

like image 386
Harsha M V Avatar asked Nov 17 '10 07:11

Harsha M V


People also ask

How do you append before an element?

The insertBefore() method inserts HTML elements before the selected elements. Tip: To insert HTML elements after the selected elements, use the insertAfter() method.

What does prepend do in jQuery?

prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use . append() ).

Is prepend before or after?

prepend() The Element. prepend() method inserts a set of Node objects or string objects before the first child of the Element .

Which jQuery DOM method is used to insert content before the selected elements?

insertBefore( target ) A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter.


2 Answers

Use before():

$('#comment-box').before('<li id="4"></li>')
like image 186
Dr.Molle Avatar answered Oct 06 '22 07:10

Dr.Molle


Wouldn't this make more sense?:

$('ul#comments_container').prepend('<li id="4"></li>');

or

$('<li id="4"></li>').hide().prependTo('Ul#comments_container').slideDown("slow");

This would allow you to add it to the beginning of a ul list to put it at the end of the list just use 'append' rather than 'prepend' or 'appendTo' also works.

like image 45
Ryun Avatar answered Oct 06 '22 09:10

Ryun