capdragon
capdragon

Reputation: 14899

How to sort $(xml).children()?

How can i sort xml elements by tagName (nodeName) when i call $(xml).children()?

I was hoping i can do something like $(xml).children().sort() but that doesn't seem to work.

Here's an example: (http://jsfiddle.net/bdMn3/1/)

Code:

var xml = "<data><itemB>more data</itemB><itemC>yes, more data</itemC><itemA>some data</itemA></data>";

var info = $("#info");

$(xml).children().each(function () {
    var xmlnode = $(this);
    info.append(this.tagName + " - " + xmlnode.text() + "<br/>");
});

Current Results:

ITEMB - more data
ITEMC - yes, more data
ITEMA - some data

Desired Results:

ITEMA - some data
ITEMB - more data
ITEMC - yes, more data

Upvotes: 1

Views: 995

Answers (1)

Mika T&#228;htinen
Mika T&#228;htinen

Reputation: 983

The sort function takes a compare function as a parameter.

$(xml).children().sort(function(a, b) { return a.tagName > b.tagName ? 1 : a.tagName < b.tagName ? -1 : 0; })

Upvotes: 4

Related Questions