breni
breni

Reputation: 35

Reorder a nodelist in javascript

I would like to sort my nodelist by the VM field Name attribute. The xml:

 <SRM>
  <HBR>
    <VM Name="mast0010">
      <FieldOne>ttttt</FieldOne>
      <Disk Name="Name One">
        <FieldTwo>aaaaa</FieldTwo>
        <FieldThree>bbbbb</FieldThree>
      </Disk>
      <Disk Name="Name Two">
        <FieldTwo>fffff</FieldTwo>
        <FieldThree>ccccc</FieldThree>
      </Disk>
    </VM>
    <VM Name="mast0003">
      <FieldOne>rrrrr</FieldOne>
      <Disk Name="Name One">
        <FieldTwo>ddddd</FieldTwo>
        <FieldThree>eeeee</FieldThree>
      </Disk>
    </VM>
  </HBR>
</SRM>

I wrote the code below:

var x=xmlDoc.getElementsByTagName("VM");        
var ax = Array.prototype.slice.call(x, 0);

for (var i=0; i<ax.length; i++) {
ax.sort(function(a, b){
    var a = ax[i].getAttribute('Name');
    var b = ax[i].getAttribute('Name');
    if(a < b) return -1;
    if(a > b) return 1;
    return 0;
    });
}

for (i=0; i<ax.length; i++) {
    document.write(ax[i].getAttribute('Name') + "<br/>");
}

It returns mast0010, mast0003 I would need mast0003,mast0010 order. Please help me out. I don't unerstand where the problem is. Thx

Upvotes: 3

Views: 1058

Answers (2)

Don't use document.write, it's from an ancient version of JavaScript and not meant to be used anymore. If you want to add nodes into an active document, use DOM manipulation functions like appendChild, insertBefore, etc.

You're also calling ax.sort a million times (or rather, once for every element in the array). That's not how you use sort, so just turn that into a single line, and rely on the sort inputs, don't reach out to your array.

Rewritten code:

ax = ax.sort(function(a,b) {
  a = a.getAttribute("Name");
  b = b.getAttribute("Name");
  return a < b ? -1 : b < a ? 1 : 0; });
});

and then insert the resulting elements into the document the proper way.

ax.forEach(function(node) {
  document.body.appendChild(node);
});

Upvotes: 2

Vikram Deshmukh
Vikram Deshmukh

Reputation: 15646

Check this working demo

Here is the sorting function fixed for you.

var x=xmlDoc.getElementsByTagName("HBR")[0].getElementsByTagName("VM");        
var ax = Array.prototype.slice.call(x, 0);

for (var i=0; i<ax.length; i++) {
ax.sort(function(a, b){
    a = a.getAttribute('Name');
    b = b.getAttribute('Name');

    if(a < b) return -1;
    if(a > b) return 1;
    return 0;
    });
}

Upvotes: -1

Related Questions