更新div列表

I have a list of divs, like :

<div class="categories" onmouseover="this.style.background='#CCCCCC'" onmouseout="this.style.background='#FFFFFF'">
    <div class="categories1">
        Andy
    </div>

    <div class="categories2">
        Link to Andy
    </div>
</div>

<div class="categories" onmouseover="this.style.background='#CCCCCC'" onmouseout="this.style.background='#FFFFFF'">
    <div class="categories1">
        Mark
    </div>

    <div class="categories2">
        Link to Mark
    </div>
</div>

...

<div class="categories" onmouseover="this.style.background='#CCCCCC'" onmouseout="this.style.background='#FFFFFF'">
    <div class="categories1">
        Yuri
    </div>

    <div class="categories2">
        Link to Yuri
    </div>
</div>

Ordered by the name inside categories1.

Through AJAX/jQuery I add to the server a new category, and after this operation I'd like to update the list on client-side.

So, I thought to these ways :

  1. Select all categories from database after the insert one, create the whole html and refresh the older one with the new one; the faster solution as coding, but if the list is so long, the overhead is big;

  2. Load from the server only the created element, browse the DOM trought jQuery, check where to put the element (checking the alphabetic order) and add it;

None of them sound nice to me, so I'll ask to you some suggestions/tips/ideas.

Thanks

Make an AJAX call to grab the new elements. Append it to your containing div. Then sort all the div's by name using ->

//get a raw array of dom nodes
var items = $('.categories1').get();

//empty out the container
$('#container').empty();

//use Array's prototype sort() method
items.sort(function(x,y) {
  return $(x).text() > $(y).text();
});

//iterate through their sorted order, appending their parent back to the container
$(items).each(function() {
    $('#container').append($(this).parent());
});

Here's a fiddle to see it in action - http://jsfiddle.net/rz3Ww/

I'd be inclined to go with your second suggestion - jQuery can very quickly grab all the elements with a class of category1 and it's trival to parse the text into an array from there. Then all you need to do is find out which element comes just before your new element, find it in the DOM, and add yours after it.

Two things come to mind after reading your question:

  1. You are talking about a list, but you're using DIVs. This isn't the end of the world, but using an unordered list (<ul>) would be more semantically appropriate.
  2. Since you bring up jQuery, this problem begs for the use of jQuery Templates plugin. You are trying to do client-side data binding, and that's exactly what jQuery Templates will help you do.