add li to middle of the ul (jquery)
Asked Answered
I

3

7

How one can add li to middle of the ul.

For example if i have list like this:

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>

And i want to add addiion li (<li>new</li>) after 3rd list?

Impure answered 15/2, 2010 at 21:22 Comment(1)
Why haven't you accepted an answer to this question yet?Ascidium
S
31
var middle = Math.ceil($("#myUL li").length / 2);
$("#myUL li:nth-child(" + middle + ")").after('<li>Item New</li>');
Stringency answered 15/2, 2010 at 21:28 Comment(1)
middle should have been Math.ceil($("#myUL").children("li").length / 2); as we might encounter nested lists. 2 centsTog
I
11

Try this out:

$('ul li:nth-child(3)').after('<li>new</li>');
Immolate answered 15/2, 2010 at 21:26 Comment(1)
this assums a fixed number of li items... better use Aquino solution. Thanks anyway :)Philender
B
0

Try this:

$('ul li:eq(2)').after(`<li>new</li>`)

Use ' or " within braces I have used ` since it was getting formatted as html.

Blairblaire answered 10/4, 2018 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.