life_of_pi life_of_pi - 1 month ago 8
Javascript Question

Sorting, element.firstChild.nextSibling.firstChild.data; JavaScript, Table

//Solved

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

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


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
    getElementsByTagName("tr")
    in an array row_tab

  2. Array with the same content
    ...

    var row_t=new Array();
    for(i=0;i<row_tab.length;i++){
    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++){
    cattosort[i]=row_tab[i].firstChild.nextSibling;
    }
    cattosort=cattosort.sort(compare);

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

    z=row_tab[i];
    row_tab[i]=row_t[k];
    row_t[k]=z;
    }
    }
    }



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

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

Answer

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

Comments