Onilol Onilol - 5 months ago 14x
Javascript Question

Clone image from different row in table

I have this table structure here:

<table id="all-prods" class="table bordered">
<tr class="product">
<img src="test" />
<td>Product Title</td>
<td style="text-align:right">
<button type="button" name="click_me">Check out the Variants!</button>
<tr style="display:none">
<tr class="table-odd" style="display:none">
<td>Variant title</td>
<td>Variant price</td>
<td style="text-align:right;">
<input id="variant-x" class="quantity field"/>
<button style="text-align:right" type="button" name="addItem">Add</button>

It's designed to be 1 row for each product , with subrows for each variant.
The contents of this table are being cloned to this one:

<table id="items" class="table bordered hidden">
<th>Item image:</th>

I can clone the variant's data with this script here:

var clone = $(this).closest('tr').clone(true);
clone.appendTo('#items tbody');

Thing is.. I can't find a way to copy the product's image as the first column in the second table.

I've tried this:Updated JSFiddle link approach but it seems like I'm failing to find the element.

Script at the moment looks like this:

var clone = $(this).closest('tr').clone(true);
var img = $(this).closest('tr').prev('tr').find('img').clone(true);
img = img.wrap("<td></td>");
clone.appendTo('#items tbody');

Could someone help?


Try like following.

$("button[name='addItem']").click(function () {
    var clone = $(this).closest('tr').clone();
    clone.prepend('<td>' + $(this).closest('tr').prevAll('.product:last').find('img')[0].outerHTML + '</td>')
    clone.appendTo('#wholesale-items tbody');