Sort XML nodes with jQuery and attach them to them

Here are the basics of the circuit ... there is more to it than this, but it gives a good idea of โ€‹โ€‹what I need to accomplish:

<item>
    <name>This is some product name to sort with dictionary sort.</name>
    <price value="29.99">$29.99</price>
</item>
<item>
    <name>This is some product name to sort with dictionary sort.</name>
    <price value="29.99">$29.99</price>
</item>

      

Below is the approach:

var node = null;
var path = null;
var items = jQuery( "item", xml );
var itemsTmp = new Array();
var itemsSorted = [];

for ( i = 0; i < items.length; i++ ) {

    // price
    itemsTmp[i] = jQuery( "price", items[i] ).attr( "value" );

}

itemsTmp.sort(function(a,b){return a-b});

for ( i=0;i<itemsTmp.length;i++ ) {

    itemsSorted[ i ] = jQuery( "price[value=" + itemsTmp[ i ] + "]", items ).parent();

}

      

The problem is that itemsSorted is now an array of jQuery objects. I need to collect all my element nodes together, but sorted, so that later I can do:

jQuery( "item", xml ).each(function() {
    alert( jQuery( "price", this ).text() );
});

      

+1


a source to share


1 answer


When adding to the itemsSorted array, you can use ... parent (). get (0); To add node to array instead of jQuery object.

Then after the last iteration:



jQuery("item", xml).remove();
jQuery.each(itemsSorted, function() {
    jQuery(xml).append(this);
});

      

Also, you should be aware that you haven't defined the "i" variable in your for-loop. This makes it a global variable and can cause a lot of weird behavior. I prefer to use jQuery.each because it also gives local scope inside the for loop :)

+3


a source







All Articles