O'Reilly logo

jQuery and JavaScript Phrasebook by Brad Dayley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required