Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a list-item at specific position

I'd like to add a <li> at a specific position, for example:

<ul id="list">     <li>Position 1</li>     <li>Position 2</li>     <li>Position 4</li> <ul> 

Let's say that I want to add a new <li> below/after <li>Position 2</li>, how can I do it using jQuery?

I've tried to do it using the code below:

$('#list li:eq(1)').append('<li>Position 3</li>'); 

But, it didn't work, because it appends the <li> inside the <li>Position 2</li>, instead add the <li> below/after the <li>Position 2</li>.

Can someone give me some help?

Thank you.

like image 700
Germanico Brismal Avatar asked May 28 '10 20:05

Germanico Brismal


People also ask

How do you add an item to a list at a specific position?

You can add an item to a list with the append() method. A new item is added at the end. If you want to add to other positions, such as the beginning, use the insert() method described later. A list is also added as one item, not combined.

How do you add an item to a specific place in a list Python?

The Python list data type has three methods for adding elements: append() - appends a single element to the list. extend() - appends elements of an iterable to the list. insert() - inserts a single item at a given position of the list.


2 Answers

You have to use after() instead of append():

Description: Insert content, specified by the parameter, after each element in the set of matched elements.

$('#list li:eq(1)').after('<li>Position 3</li>'); 

The documentation of append() clearly says:

Insert content (...) to the end of each element.


For completeness:

Note that :eq(n) matches the nth element of the matching element set, whereas :nth-child(n) matches the nth child of the parent.

like image 165
Felix Kling Avatar answered Oct 09 '22 22:10

Felix Kling


You should use after() or insertAfter()
http://api.jquery.com/category/manipulation/dom-insertion-outside/

like image 35
emmanuel Avatar answered Oct 09 '22 23:10

emmanuel