Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort table rows based on their Class Names

Tags:

jquery

I want to rearrange table rows based on their Class names.
Below is my HTML code.

<table>
 <tr class="a4"><td>4</td></tr>
 <tr class="a6"><td>6</td></tr>
 <tr class="a1"><td>1</td></tr>
 <tr class="a2"><td>2</td></tr>
 <tr class="a5"><td>5</td></tr>
 <tr class="a3"><td>3</td></tr>
</table>

So now, with class name a1 should display first, likewise a2 second.. etc..

Please someone help me

like image 479
Reddy Avatar asked Jul 18 '11 08:07

Reddy


2 Answers

If you don't want to rely on an external plugin, you can extract the numbers from the class names using match() and sort the elements using the built-in sort() method.

From there, you can use append() to reorder the table rows (it will remove each row from the table then re-add it at the proper position):

$("table").append($("tr").get().sort(function(a, b) {
    return parseInt($(a).attr("class").match(/\d+/), 10)
         - parseInt($(b).attr("class").match(/\d+/), 10);
}));

You can see the results in this fiddle.

like image 77
Frédéric Hamidi Avatar answered Oct 07 '22 04:10

Frédéric Hamidi


You could use this plugin and to something like:

jQuery.fn.sortElements = (function(){

    var sort = [].sort;

    return function(comparator, getSortable) {

        getSortable = getSortable || function(){return this;};

        var placements = this.map(function(){

            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,

                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );

            return function() {

                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }

                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);

            };

        });

        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });

    };

})();
// do the sorting
$('tr').sortElements(function(a, b){
    return $(a).attr('class') > $(b).attr('class') ? 1 : -1;
});

fiddle here: http://jsfiddle.net/ZV5yc/1/

like image 39
Nicola Peluchetti Avatar answered Oct 07 '22 02:10

Nicola Peluchetti