Inserting Items into a List

var item = "New Item"; var nextItem = false; $("ul li").each(function(i, item){   if ($(item).html() > newItem){     nextItem = item;     return false; }}); if (!nextItem){  $("ul").append($("<li></li>").html(newItem)); } else {  $(nextItem).before($("<li></li>").html(newItem));}

Another common task when dynamically manipulating web pages is to insert elements into a list. But what if the list needs to be sorted? There are a few different ways to do this.

One way to add the item would be to iterate through the list elements until you find one that is larger than the new item. Then insert the new item before that existing item. If a larger item is not found, just append the item to ...

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.