dimvcl
dimvcl

Reputation: 299

Bring td to the top of a table

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>

Upvotes: 0

Views: 368

Answers (2)

showdev
showdev

Reputation: 29168

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>

Upvotes: 2

Ortiga
Ortiga

Reputation: 8814

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

Upvotes: 1

Related Questions