Ewr Xcerq Ewr Xcerq - 1 month ago 6
jQuery Question

Selector for a list-jquery newb

I have a table like this

<table>
<tr>
<td>Item1<td>
<td><p>Description<p><br><td>
</tr>
<tr>
<td>Item2<td>
<td><p>Description1</p><p>Description2</p><br><td>
</tr>
<tr>
<td>Item3<td>
<td><p>Description3<p><br><td>
</tr>
</table>


Here is my javascript to get an array of items

var iList = document.querySelectorAll('td:first');


and here is to get all mapped
td p
content

var iDesc = document.querySelectorAll('td:second p');


I would like to create a mapped then sort its content in the onload event by the way. Is what I am doing correct ? I mean the selector
td:first
and second with my example table

In the example above there is one
td
element containing 2
p
's

Answer

You should run a loop for each tr element and get the keys and values from td elements. Next, push them into an array.

var arr = new Array();
$('table tr').each(function() {
    var $row = $(this);
    var key = $row.find('td:first').html();
    var value = $row.find('td:last').html();
    arr.push([key, value]);
});

Finally, sort the array by it's first index.

arr.sort(function(a, b) {
    var valueA, valueB;
    valueA = a[0]; // Where 1 is your index, from your example
    valueB = b[0];
    if (valueA < valueB) {
        return -1;
    }
    else if (valueA > valueB) {
        return 1;
    }
    return 0;
});

Live Demo

Comments