How to sort divs according to their id using jQuery?

前端 未结 3 873
太阳男子
太阳男子 2020-12-01 19:31

I have a set of divs with random ids:

3条回答
  •  無奈伤痛
    2020-12-01 19:46

    There are plugins and the like to do sorting of elements. If you plan on actually re-ordering the DOM elements, you should probably use one of them.

    If you just want a sorted list of the divs, you can use Javascript - since arrays can be sorted using a custom comparison function. You can convert the selected set of

    s into an array using toArray() and then sort them using this mechanism.

    $('#container > div').toArray().sort( function(a,b) { a.id - b.id } );
    

    You could also use the detach() and appendTo() method to remove and the re-insert the elements in sorted order. However, this may not be the most efficient way to re-order the DOM elements.

提交回复
热议问题