I have a table and I want to clone it without its children. Note that I simplified the markup for brevity, the table has many properties and event handlers which I also want to copy.
<table data-x="..." class="a b c">
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
.
.
.
</table>
I don't want to copy all then delete the children afterwards, I'm not sure but I think it's not efficient.
I have a table and I want to clone it without its children. Note that I simplified the markup for brevity, the table has many properties and event handlers which I also want to copy.
<table data-x="..." class="a b c">
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
.
.
.
</table>
I don't want to copy all then delete the children afterwards, I'm not sure but I think it's not efficient.
Share Improve this question edited May 14, 2015 at 6:20 kazinix asked May 14, 2015 at 6:08 kazinixkazinix 30.2k36 gold badges111 silver badges162 bronze badges 7-
3
Then why don't you just create
table
using jquery – Tushar Commented May 14, 2015 at 6:09 -
1
I don't think
jQuery
has that but you can do that with plain JavaScript.node.cloneNode()
. This won't copy attached event listeners - developer.mozilla/en-US/docs/Web/API/Node/cloneNode – Vigneswaran Marimuthu Commented May 14, 2015 at 6:11 - @Tushar see edited post. I just made the markup simple. – kazinix Commented May 14, 2015 at 6:12
- Please post the plete HTML in jsBin or PasteBin and specify which all are you planning to retain in the cloned copy – Amal Dev Commented May 14, 2015 at 6:14
- @VigneswaranMarimuthu I think you should post that as an answer, of all the response, yours is a real answer... – kazinix Commented May 14, 2015 at 6:19
5 Answers
Reset to default 7I don't think you can clone just the element without it's children using jQuery
but you can do that with plain JavaScript. node.cloneNode()
. This won't copy attached event listeners
cloneNode
I think you should use cloneNode()
var $table = $('table');
var clone = $table[0].cloneNode(); //without deep property
Demo: Fiddle
Note: Any jQuery listeners and data associated won't be copied
You can do it easily with jQuery .clone()
:
var $new_table = $('table').clone();
$newtable.html(''); // which returns <table></table>
If i think then you can create a new table itself using jquery. Since you did not provide the code that you are using i am giving you an example.
<div id='tabdiv'>
</div>
simple jquery code:
$('#tabdiv').html('<table></table');
This will create a new empty table in the div with this new table
Try this: You can Remove the childrens if you dont need them.
var newtable = $('table').clone();
newtable.find('tr').remove(); // or you can remove anything you want to remove from it
Now in new table you will have table without any rows. Hope this works.