0

How can I bring a td to the top of a table? I have something like this:

    <table>
    <tr><td>...</td></tr>
    <tr>
    <td id="pp" class="text-right"><!-- I want this td in the top of table when a is clicked-->
        <a ...>
        <i class=""></i>
        </a>
    </td>
    </tr>
<tr><td>...</td></tr>
</table>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
dimvcl
  • 289
  • 1
  • 3
  • 13
  • Possible duplicate of [Move Rows up and down in html table](http://stackoverflow.com/questions/4321320/move-rows-up-and-down-in-html-table) – Whitecat Nov 10 '15 at 00:47

2 Answers2

2

One method is to use jQuery's prepend() to move the desired <tr> (row) to the top of the table.
Note that:

If a single element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).

If there is more than one target element, however, cloned copies of the inserted element will be created for each target except for the last one.

In my example, I use closest() to traverse from the clicked <td> to its containing <tr> so that the entire row can be moved.

jQuery('#pp').on('click', function() {
  jQuery(this).closest('tr').prependTo('table');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr><td>...</td></tr>
  <tr><td>...</td></tr>
  <tr><td id="pp"><a><i class="">click to move this row to the top</i></a></td></tr>
  <tr><td>...</td></tr>
</table>
showdev
  • 28,454
  • 37
  • 55
  • 73
  • For some reason it doesn't work with my code, I use bootstrap and the table class name is 'table-condensed' I generate the the table content , something like this: {{product.code}} {{product.name}} {{product.typeString}} {{product.node?product.node.name}} {% if request is defined %} ... – dimvcl Nov 10 '15 at 01:30
  • @dimvcl Please use the [edit button](http://stackoverflow.com/posts/33620961/edit) to update the code in your question. If possible, create a working example of your code so we can reproduce the problem. – showdev Nov 10 '15 at 17:28
1

You have to move the entire tr to the top. You can find the closest tr relative to the link, then prepend it to your table:

$("#pp a").on('click', function(){
    var tr = $(this).closest('tr');
    tr.prependTo(tr.closest('table'))
});

See fiddle

Ortiga
  • 8,455
  • 5
  • 42
  • 71