Search code examples
javascriptalphabetical

insert new item in a sorted list of divs


<list>
    <div>abacus</div>
    <div>abstract paint</div>
    <div>australian coco</div>
     .........
     .........
     .........
    <div>mango</div>
    <div>parrot</div>
    <div>salt</div>
    <div>upi</div>
</list>

The "list" tag is inside the body of a HTML document... "list" tag contains over 5000 divs... as it is a very big number, I present a part of it...

I need to insert a new div (like <div>apache</div>) among these divs alphabetically according to these divs innerHTML (innerHTML contains only alphabets and numbers, no sign)... but the problem is if I use insertBefore() method, I will get the div at the end of the list... How can I do that...??

please don't use any jQuery... only Javascript...


Solution

  •  var list         = document.getElementsByTagName('list')[ 0 ],
         DOMitems     = list.getElementsByTagName('div'),
         items        = Array.prototype.slice.call( DOMitems );
    
    function addItem( text ) {
        var position          = 0,
            newElem           = document.createElement('div');
            newElem.innerHTML = text;
    
        items.push( newElem );
        items.sort(function( a, b ) {
            return a.innerHTML.localeCompare( b.innerHTML );
        });
    
        position = items.indexOf( newElem );
        list.insertBefore( newElem, DOMitems[ position ] );
    }
    
    addItem('apache');
    

    Fiddle