Search code examples
jqueryclonesiblings

jQuery - how to select a cell AND its previous sibling


I have the following table structure.

<table>
    <tr>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
    </tr>
    <tr>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
    </tr>
</table>

What I need to do clone all the cells with a class of "selectable", AND it's immediate previous sibling, and insert the clones in a new row. In other words, i need the result to be:

<table>
    <tr>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
    </tr>
    <tr>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
    </tr>
    <tr>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
    </tr>
    <tr>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
    </tr>
</table>

I can successfully clone the cells with a class of "selectable" by using the following. (I know this isn't valid markup as the 'TR' tags are missing. Just trying to shorten my example as much as possible.)

$('tr').each(function(){
    $(this).after($(this).find('td.selectable').clone());
})

However, I cannot work out how to include the previous sibling in the clone as well.

Can anyone point me in the right direction?

Thanks


Solution

  • You can use prev() to get the previous sibling, and then addBack() to merge the two together. To insert the new row, just create it, and append the merged collection to it by using append():

    $(this).after( $('<tr>').append( $(this).find('td.selectable').prev().addBack().clone() ) );
    

    Here's a fiddle