views:

55

answers:

4

I'm developing an application with javascript. What I need is to have divs with id's (1,2,3...) and be able to insert a div between, for example, 2 and 3, with jquery, and then have that be the new three, and three becomes four, four becomes five, etc. I've got the div insertion working, I just need to know how to reorder the divs. Any ideas?

+2  A: 

After you inserted the new div, you can do this:

var i = 1;
$('div').each(function() {
    $(this).attr('id', i++);
});

Replace $('div') by your own selector.

Remember also that, depending on which version of HTML you use, id's can't start with a number.

edwin
Does HTML5 loosen up the "id" value rules?
Pointy
Yes. Or at least it was a proposal for HTML5: id's could contain anything, so even id="+*(*%*^{|`" would be valid. (I still don't know what to think of it :-)
edwin
you could also use the index given by each() instead of maintaining a counter.
tster
A: 

I'm pretty sure that you get things back in DOM order from jQuery selectors, so couldn't you just find the parent element, select the child <div> elements, and then .each() through the list?

Pointy
+1  A: 

You can't start IDs with a numeric value, but regardless of that you'd do something like

// set a data value in the div you have just inserted into the dom and set a variable theID to the current ID you have just inserted.

$(this).data('inserted', true);
var theID = $(this).attr('id'); // this will be 3.


// now to update the other divs.
$('div').each(function() {
    if($(this).attr('id') >= theID && !$(this).data('inserted')){
        $(this).attr('id', $(this).attr('id') + 1);
    }
});

// now set the data inserted to false for future updates
$('div#3').data('inserted', false);
Damon Skelhorn
+1  A: 
$(function() {

  reorder();

  $('#click').click(function() {

    $('<h2>hello world blah!</h2>').insertAfter('.content h2:eq(1)');
    reorder();
  });

});

function reorder() {
 $('.content h2').each(function(i) {
    $(this).attr('id', 'order_'+(i+1));
 // alert( parseInt(this.id.split('_')[1]) ); // this is the id #
 });
};
aSeptik