life_of_pi life_of_pi - 1 year ago 132
Javascript Question

Sorting,; JavaScript, Table


I am trying to navigate trough a DOM tree and sort the elements.

<td>B</td> <---------Take this as a criterion
<td>A</td> <------------- same

var compare=function(x, y) {
var xValue=x.innerHTML;
var yValue=y.innerHTML;
if(xValue==yValue) return 0;
else if(xValue>yValue) return 1;
else return -1;

And my algorithm:

  1. Push the
    in an array row_tab

  2. Array with the same content

    var row_t=new Array();
    row_t[i]=row_tab[i]; //2.

    var cattosort=new Array(); //Array for the second td-elements
    for(i=0;i<row_tab.length; i++){

    for(i=0;i<cattosort.length; i++){
    for(var k=0; k<row_t.length; k++){
    //Here should be the mistake in the navigation,but formal it
    //seems true for me (row_t[k]>
    //the text of the next sibling of the first child->the text of the 2. element


However, there is no error, but my programme doesn't react. Do I use the proper command />(see the comments under the if in the code)/?

PS: I'm not permitted to use libraries, if that matters.

Answer Source

I'm going to suggest that you back up and find a good algorithm for sorting table rows. Since this appears to be homework, I'm going to suggest the algorithm without giving you the exact code.

The general algorithm I've seen used many times does the following:

  1. Build an array of objects where each object in the array contains a row DOM element reference and the content to sort by.

  2. Sort that array using a custom sort function. Since the content is in an object along with the DOM reference to the containing row, this will sort both together.

  3. Now that you have a sorted array, simply reinsert the each row into the table one after another in the order of the sorted array. This moves whole row elements around and does not actually reassign content.

Here's a related example from another answer: How can i use javascript to sort the tables by column? Can not use jquery here. I'm using javascript to load a table from an xml file

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download