开发者

Javascript only - sort a bunch of DIVs [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Easiest way to sort DOM nodes?

I have a list of DIVs, like this :

<div id="list">
    <div id="categorie5.1-4">4</div>
    <div id="categorie5.1-3">3</div>
    <div id="categorie5.1-5">5</div>
    <div id="categorie5.1-1">1</div>
    <div id="categorie5.1-2">2</div>
</div>

and I want to sort them, using Javascript only (no Jquery) to have a result like this :

1
2
3
4
5

If needed, I can use the end of the DIV ids : "categorie5.1-4" (server-side I can define the DIV ids to embedded the wanted order)

Thank you very much for your help!


Here is the complete code :

<html>
<head>
<script type="text/javascript">
function sortdiv() {
var container = document.getElementById("list");
var elements = container.childNodes;
var sortMe = [];
for (var i=0; i<elements.length; i++) {
    if (!elements[i].id) {
        continue;
    }
    var sortPart = elements[i].id.split("-");
    if (sortPart.length > 1) {
        sortMe.push([ 1 * sortPart[1] , elements[i] ]);
    }
}
sortMe.sort(function(x, y) {
    return x[0] - y[0];
});
for (var i=0; i<sortMe.length; i++) {
    container.appendChild(sortMe[i][1]);
}
document.getElementById("button").innerHTML = "done.";
}
</script>
</head>
<body>
<div id="list">
    <div id="categorie5.1-4">4</div>
    <div id="categorie5.1-开发者_如何学JAVA3">3</div>
    <div id="categorie5.1-5">5</div>
    <div id="categorie5.1-1">1</div>
    <div id="categorie5.1-2">2</div>
</div>
<div id="button"><a href="#" onclick="sortdiv();">sort!</a></div>
</body>
</html>


First you have to get all divs:

var toSort = document.getElementById('list').children;

toSort will be a NodeList. You have to transform it to an array:

toSort = Array.prototype.slice.call(toSort, 0);

and then you can pass a callback to the sort method:

toSort.sort(function(a, b) {
    var aord = +a.id.split('-')[1];
    var bord = +b.id.split('-')[1];
    return aord - bord;
});

Edit: As @Lekensteyn already noted, comparing IDs only works if you have only single digit numbers. Fixed it to support arbitrary numbers.

You have to loop over this array and append the elements again:

var parent = document.getElementById('list');
parent.innerHTML = "";

for(var i = 0, l = toSort.length; i < l; i++) {
    parent.appendChild(toSort[i]);
}

Edit: fixed typo

DEMO

Update: If you have so many elements, caching of the IDs could be done like so:

var cache = {
   add: function(id) {
       var n = +id.split('-')[1];
       this[id] = n;
       return n;
   }
};

toSort.sort(function(a, b) {
    var aord = cache[a.id] || cache.add(a.id);
    var bord = cache[b.id] || cache.add(b.id);
    return aord - bord;
});


You should put the elements in an array, run a sort function over the elements, and re-append the sorted elements to the container.

// container is <div id="list">
var container = document.getElementById("list");
// all elements below <div id="list">
var elements = container.childNodes;
// temporary storage for elements which will be sorted
var sortMe = [];
// iterate through all elements in <div id="list">
for (var i=0; i<elements.length; i++) {
    // skip nodes without an ID, comment blocks for example
    if (!elements[i].id) {
        continue;
    }
    var sortPart = elements[i].id.split("-");
    // only add the element for sorting if it has a dash in it
    if (sortPart.length > 1) {
        /*
         * prepare the ID for faster comparison
         * array will contain:
         *   [0] => number which will be used for sorting 
         *   [1] => element
         * 1 * something is the fastest way I know to convert a string to a
         * number. It should be a number to make it sort in a natural way,
         * so that it will be sorted as 1, 2, 10, 20, and not 1, 10, 2, 20
         */
        sortMe.push([ 1 * sortPart[1] , elements[i] ]);
    }
}
// sort the array sortMe, elements with the lowest ID will be first
sortMe.sort(function(x, y) {
    // remember that the first array element is the number, used for comparison
    return x[0] - y[0];
});
// finally append the sorted elements again, the old element will be moved to
// the new position
for (var i=0; i<sortMe.length; i++) {
    // remember that the second array element contains the element itself
    container.appendChild(sortMe[i][1]);
}

You can test this code at http://jsfiddle.net/4gkDt/1/


Javascript arrays has a sort function.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

you can make sort the childnodes list node on innerHTML (in your example) or some other key.

This shows how to get the list node http://codingrecipes.com/documentgetelementbyid-on-all-browsers-cross-browser-getelementbyid

so something like

document.getElementById("list").children.sort(yourSortFunction)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜