0

I know I can use append() to add an 'li' to the end of a list, but how would I add it to a specific index? Would I just have to manipulate an array and then refresh the list with the updated array? Or is there already a function written in jQuery that allows me to do this?

I have tried looking in the jQuery API Documentation, but I just started with JavaScript earlier this week and I am having trouble understanding everything.

9 Answers9

0

Use a combination of nth-child() and after

$( ".todos li:nth-child(2)" ).after(todoLi);

If you want to insert todoLi after the 2nd item in the list.

Tuan Anh Hoang-Vu
  • 1,994
  • 1
  • 21
  • 32
0

Here is a quick snippet to show you how .after() works.

$('ul li:eq(1)').after("<li>hello world</li>")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
xengravity
  • 3,501
  • 18
  • 27
0

You could try it like this, where index is whatever spot you'd like to insert at.

var index = 3;
$('ul li:nth-of-type('+index+')').after('<li><a href="/link">Zac was here</a></li>')
zacbrac
  • 35
  • 5
0
$('ol li').eq(index).after(your_element);
Samurai
  • 3,724
  • 5
  • 27
  • 39
0

Just figure out which element is in the middle and insertAfter it.

var newLi = $('<li></li')
var halfway = Math.floor($('ol > li').length);
newLi.insertAfter($('ol > li')[halfway]);
Dylan Watt
  • 3,357
  • 12
  • 16
0

You can try using the jQuery .after() method utilizing the :nth-child() selector. For example, if you wanted to try adding your li after the 2nd li and before the 3rd

$( "ul li:nth-child(2)" ).after('<li>added!</li>');
janamargaret
  • 126
  • 2
0

jQuery has a function to add an element after or before a node (.before()/.after()).

You can then use .eq() to select an element and place your element where you want.

Here a little function that do what you want (0 based index). It is important to check if the index element exist, else it will never be put in the DOM:

function appendAt($what, $to, index){
    var $target = $to.children().eq(Math.max(0, index));
    if($target.length !== 0){
        $target.before($what);
    }else{
        $what.appendTo($to);
    }
}

//Use it like that
appendAt($('<li>'), $('.todos'), 5); //The li with become the 6th element.
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
0
<ol class="list">
    <li><a href="#">list 1</a></li>
    <li class="active"><a href="#">list 2</a></li>
    <li><a href="#">New Tag</a></li>
    <li><a href="#">list 3</a></li>
    <li><a href="#">list 4</a></li>
</ol>

$('li.active').after('<li><a href="#">New Tag</a></li>');
0

Simple way would be

var newLi="<li>This is test</li>";
$(".list li:nth-child(2)").after(newLi);

Remember the child index starts from 1, so 2 here means after the second li

Raj Nandan Sharma
  • 3,694
  • 3
  • 32
  • 42