How can I reorder/sort a NodeList in JavaScript?

前端 未结 3 2117
Happy的楠姐
Happy的楠姐 2021-02-14 00:27

I have what I think should be a straightforward question; let me quickly explain:

In my JavaScript, food.xml is read in with:

getMenuXml.ope         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-14 01:15

    You can order the elements of the NodeList, if you convert them to an array first:

    var foods = xmlDoc.getElementsByTagName("food");
    var foodsArray = Array.prototype.slice.call(foods, 0);
    

    Then you can use the sort method:

    foodsArray.sort(function(a,b) {
        var aCat = a.getElementsByTagName("category")[0].childNodes[0].nodeValue;
        var bCat = b.getElementsByTagName("category")[0].childNodes[0].nodeValue;
        if (aCat > bCat) return 1;
        if (aCat < bCat) return -1;
        return 0;
    });
    

    This is highly dependent on your XML schema though - if, for example, you had foods which were in more than one category they would only be sorted by the first category in the code above.

提交回复
热议问题