eggman eggman - 6 months ago 50
Javascript Question

Use jquery to move a td in a tr

I'm looking for a way to dynamically move a

td
from one place to another (within the same
tr
).

Please have a look at this fiddle that demonstrates my problem and also some psuedo-code.

http://jsfiddle.net/Qsys7/847/

I hope to be able to loop through all
td
´s and check for images in this manner:

$('#original > tbody > tr').each(function(index, value) {
var tdToMove;
// Check if elem has an image as a child
//if so, move it...
});

Answer

You can do it like following.

$('#original > tbody  > tr').each(function(index, value) {
    var td = $('td:first', this);
    $(this).append(td)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="original">
  <tbody>
    <tr>
      <td></td>
      <td><strong>Name</strong></td>
    </tr>
    <tr>
      <td><img src="http://mario.nintendo.com/img/mario_logo.png" alt="" width="100" height="65" /></td>
      <td>Mario</td>
    </tr>
    <tr>
      <td><img src="http://www.mariowiki.com/images/thumb/a/a0/Ice_Luigi_artwork.jpg/150px-Ice_Luigi_artwork.jpg" alt="" width="100" height="65" /></td>
      <td>Luigi</td>
    </tr>
  </tbody>
</table>