Tim
Tim

Reputation: 307

tSort on jQuery object

I'm trying to sort the results of a jQuery selection with tSort.

HTML:

<div sort="2"></div>
<div sort="3"></div>
<div sort="1"></div>
<div sort="4"></div>
<div sort="6"></div>
<div sort="5"></div>

Javascript:

<script>
    $sort_order = $('div').tsort({attr:'sort'});
</script>

I want the result to be: 1,2,3,4,5,6 in the jQuery object, not yet inserted into the page. Is this possible with tSort, or should I write my own algorithm?

Upvotes: 3

Views: 2891

Answers (2)

chris97ong
chris97ong

Reputation: 7060

It is easier to do it if there is a wrapper of all the div elements.

HTML:

<div id="wrapper">
<div sort="2">2</div>
<div sort="3">3</div>
<div sort="1">1</div>
<div sort="4">4</div>
<div sort="6">6</div>
<div sort="5">5</div>
</div>

Javascript (with jQuery):

var $wrapper = $('#wrapper');
$wrapper.find('div').sort(function (a, b) {
    return +a.getAttribute('sort') - +b.getAttribute('sort');
})
.appendTo($wrapper);

Working demo.


In response to @Tim's comment, you can place the elements that do not have the sort attributes at the back of the wrapper element easily, even without jQuery.

Assuming that this is your HTML:

<div id="wrapper">
<div style="color:red;">red color, without sort attribute</div>
<div style="color:red;" sort="7">red color (sort attribute=7)</div>
<div sort="2">2</div>
<div sort="3">3</div>
<div sort="1">1</div>
<div sort="4">4</div>
<div sort="6">6</div>
<div sort="5">5</div>
</div>

You can place the element(s) that do not have the sort attribute by having this as your Javascript:

// As shown earlier above,
var $wrapper = $('#wrapper');
$wrapper.find('div').sort(function (a, b) {
    return +a.getAttribute('sort') - +b.getAttribute('sort');
})
.appendTo($wrapper);

// New code to add:
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++) {
    if(divs[i].getAttribute('sort') == null || divs[i].getAttribute('sort') == undefined) {
        divs[i].parentNode.appendChild(divs[i]);   
    }
}

Working demo.

Upvotes: 2

Anton
Anton

Reputation: 32581

clone it before using .tsort

 $sort_order = $('div').clone().tsort({attr:'sort'});

DEMO

Upvotes: 1

Related Questions