Reputation: 12512
I have a table and a link below it. I need to be able to click that link, copy the table above, with all its contents and paste it below that original table.
<table>
...
</table>
<br>
<a href="#" id="copyTbl">copy</a>
I tried something like this, but failed:
$("#copyTbl").click(function() {
$(this).closest("table").html().clone().appendTo("br");
});
Am I stringing it improperly?
Upvotes: 0
Views: 266
Reputation: 46657
Try something like this, short and simple:
edit: be careful when cloning elements with IDs :P
edit: handle IDs when cloning http://jsfiddle.net/wfqa7/8/
Upvotes: 2
Reputation: 160
Closest would mean the link is inside the table. Many ways to do this: http://jsbin.com/aqamok
Upvotes: 1
Reputation: 360056
Am I stringing it improperly?
Yes and no. .html()
returns a string, which does not have a .clone()
method.1 Either clone the elements, or use .html()
:
$("#copyTbl").click(function() {
$(this).closest("table").clone().insertAfter("br");
// or
$("br").after($(this).closest("table").html());
});
1Strings are immutable, so there's no need for a clone method.
Upvotes: 1
Reputation: 78770
There are a few issues there. closest
looks for the first matching ancestor. Since the link is not contained within the table, that will not match. You will need to match it different, maybe an id
or some other selector based on your full html structure.
2nd, you cannot append to a br
since appendTo
places the element inside and br
has no "inside". You want to use insertAfter
instead.
EDIT: and as pointed out by SLaks, drop the html
and clone the table, you can't clone the string.
Upvotes: 4
Reputation: 888283
.html()
returns a string.
You can't clone a string.
You should either call .clone()
to return new DOM nodes or .html()
to return a raw HTML string, but not both.
Also, you can't put a table inside a <br />
; you should call insertAfter
; not appendTo
.
Upvotes: 3