Question

Is there a way to copy an element without copying it's children?

My goal is to duplicate a table, along with all classes, inline styles, etc. But I do not want to copy any of the table element's children.

I realize I could copy the entire table and then remove the children from the copy. But I want to minimize screen flicker and I seem to recall there are problems manipulating elements before they are visible in the DOM.

Any suggestions?

Was it helpful?

Solution

Have you considered using native cloneNode? The argument controls whether children should be cloned as well.

var clone = table.cloneNode(false);

This does not clone event handlers though. I'm not sure about styles set via the DOM API (probably not).

OTHER TIPS

use .cloneNode

var t = document.createElement("table");
t.setAttribute("style",'background:#0F0; font-size:12px;');
var tr = document.createElement("tr");
var td = document.createElement("td");
td.appendChild(document.createElement("input"));
tr.appendChild(td);
t.appendChild(tr);
var clone = t.cloneNode();
console.log(clone);
//outputs 
//<table style="background:#0F0; font-size:12px;"></table>

This is just another way to do it, probably the ugliest one so far posted, but I'm just adding to the possibilities. If it were me, I would use the one by Felix Kling.

It basically gets the outerHTML and innerHTML substracting one to the other: table.prop('outerHTML').replace(table.prop('innerHTML'), '');. Here's a demo.

HTML

<table class="some-class" style="border:1px solid #000" id="t">
    <tr>
        <td>first</td>
    </tr>
</table>

JS

$(function () {
    $('#t').addClass('another-class');
    var table = $('#t')
    var html = table.prop('outerHTML').replace(table.prop('innerHTML'), '');
    $('body').append($(html).append('<tr><td>second</td></tr>'));
});

CSS

.some-class {
    color: #00F
}
.another-class {
    color: #00F;
    font-size: 18px;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top