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.
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.
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.
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 n
th element of the matching element set, whereas :nth-child(n)
matches the n
th child of the parent.
You should use after()
or insertAfter()
http://api.jquery.com/category/manipulation/dom-insertion-outside/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With