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?

PetersenDidIt
  • 25,562
  • 3
  • 67
  • 72
mkoso
  • 241
  • 1
  • 3
  • 4

3 Answers3

31
var middle = Math.ceil($("#myUL li").length / 2);
$("#myUL li:nth-child(" + middle + ")").after('<li>Item New</li>');
g3rv4
  • 19,750
  • 4
  • 36
  • 58
Francisco Aquino
  • 9,097
  • 1
  • 31
  • 37
  • 2
    middle should have been Math.ceil($("#myUL").children("li").length / 2); as we might encounter nested lists. 2 cents – jronnybravo Nov 06 '13 at 07:09
11

Try this out:

$('ul li:nth-child(3)').after('<li>new</li>');
PetersenDidIt
  • 25,562
  • 3
  • 67
  • 72
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.

IKavanagh
  • 6,089
  • 11
  • 42
  • 47