2

I am trying to sort the <tr> elements within a <table> that looks like this:

Before

<table>
  <tbody>
    <tr id="foo">...</tr>
    <tr id="bar">...</tr>
    <tr id="baz">...</tr>
    <tr id="qux">...</tr>
  </tbody>
</table>

Suppose I want to sort the rows so that the table becomes like this:

After

<table>
  <tbody id="table">
    <tr id="foo">...</tr>
    <tr id="qux">...</tr>
    <tr id="baz">...</tr>
    <tr id="bar">...</tr>
  </tbody>
</table>

I can do this by using a sequence of jquery scripts:

$('#table').append($('#qux'));
$('#table').append($('#baz'));
$('#table').append($('#bar'));

but I want to make the scripts into one, and when I try:

$('#table').append($('#qux,#baz,#bar'));

on the original table, it does not seem to have any effect. Why is this not working? Is there a way to do this in one command?

Shikiryu
  • 10,180
  • 8
  • 49
  • 75
sawa
  • 165,429
  • 45
  • 277
  • 381

4 Answers4

1

From the docs

The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

So you are adding them in the same order they already are.

a better oliver
  • 26,330
  • 2
  • 58
  • 66
1

This works:

$('#table').append($('#qux'),$('#baz'),$('#bar'));

If you try this and inspect elements with a debugger

var elements = $('#qux, #baz, #bar');
$('#table').append(elements);

you can see what jquery is doing: it loads the element from your selector, but they are in the order with which they appear in the DOM! (bar, baz and quz). So the append method is working but it is appending them in the same order!

Daniele Armanasco
  • 7,289
  • 9
  • 43
  • 55
1

Alright, I made some test and here's why it doesn't work the way you want :

http://jsfiddle.net/9V2Xr/ Here, you can see that, if it comes in order in the DOM (it was a first try from another table), it works.

But then http://jsfiddle.net/9V2Xr/1/ here, if it's your original table, you can see that when you do

var sort = $('#qux,#baz,#bar').detach();
console.log(sort);

In the log, you'll find bar then baz and finally qux. Conclusion, it takes the order from the DOM

EDIT Basically, my test was useless, it'es explained in the doc.

So, main solution would be to chaining append() or using multiple selector $('#qux'), $('#baz'),$('#bar') instead of $('#qux,#baz,#bar')

Shikiryu
  • 10,180
  • 8
  • 49
  • 75
0

You can chain jquery methods:

$('#table').append($('#qux')).append($('#baz')).append($('#bar'));
AGB
  • 2,378
  • 21
  • 37