Question

I have three groups (td) of a div and a link, I want to place the link before the div in each of these groups (td). I tried with after() but to no success.. Is there a easy method to do this?

I have this structure:

<table>
    <tr>
        <td>
            <div>Text</div>
            <a href="#">Link</a>
        </td>
        <td>
            <div>Text</div>
            <a href="#">Link</a>
        </td>
        <td>
            <div>Text</div>
            <a href="#">Link</a>
        </td>
    </tr>
</table>
Was it helpful?

Solution

If you want the a element to be the first child, use the following:

Example Here

$('table td a').each(function(){
    $(this).prependTo($(this).parent());
});

Alternatively, you could also use this if you only want it to be inserted before its previous sibling.

Example Here

$('table td a').each(function(){
    $(this).insertBefore($(this).prev());
});

OTHER TIPS

A non-jQuery alternative:

[].slice.call(document.querySelectorAll('td')).forEach(function(td) {
    td.insertBefore(td.children[1], td.children[0]);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top