50

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.

Germanico Brismal
  • 501
  • 1
  • 4
  • 3

4 Answers4

85

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
9

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

emmanuel
  • 765
  • 8
  • 15
3
$('<option val="position3">Position3</option>').insertAfter('#list :nth-child(<give childnumber here>)')

index start with 1

jay
  • 347
  • 1
  • 3
  • 11
2

Check insertAfter here

Teja Kantamneni
  • 17,402
  • 12
  • 56
  • 86