According to mdn, querySelectorAll returns a static NodeList. In my example below, clicking the copy row
button will deep copy row0
container of checkboxes to row1
and append it to the DOM. However, it also seems to copy the live state of the checked
property of checkboxes. Additionally I noticed the id
properties of the new checkboxes were not updated. How can I deep copy an element in its intial state and then update its id
properties?
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>static copy test</title>
<script type="module">
class CopyClass {
row0 = document.querySelectorAll('#row0')[0];
copyRow = () => {
const row1 = this.row0.cloneNode(true);
row1.querySelectorAll('#cb0')[0].id = 'cb2';
row1.querySelectorAll('#cb1')[0].id = 'cb3';
this.row0.insertAdjacentElement('afterend', row1);
};
constructor() {
document.getElementById('copy').addEventListener('click', this.copyRow);
}
}
new CopyClass();
</script>
</head>
<body>
<label>check a checkbox and then click button to statically copy</label>
<button type="button" id="copy">copy checkboxes</button>
<div id="row0">
<div id="col0">
<input type="checkbox" id="cb0" />
</div>
<div id="col1">
<input type="checkbox" id="cb1" />
</div>
</div>
</body>
</html>