- This topic is empty.
Viewing 1 post (of 1 total)
Viewing 1 post (of 1 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Confused by cloneNode and non-live node lists.
Please excuse what may be a very basic question – I very rarely use javascript and am a little confused.
I’m making a form and don’t know how many times a fieldset will be needed for each entry, so I’ve written a duplicate()
function.
The fieldset html is, in brief:
<div>
<fieldset>
inputs, labels, etc
<fieldset>
</div>
My understanding was that if I targetted the fieldset with getElementById followed by getElementByTagName I would have an HTMLCollection that was a live list (not what I wanted since I want to duplicate the fieldset without duplicating input values already entered). I therefore used the following:
var illness = document.querySelectorAll('#illness')[0];
var fieldset = document.querySelectorAll('#illness > fieldset')[0];
function duplicate() {
var dupe = fieldset.cloneNode(true);
illness.appendChild(dupe);
}
No joy. Was appending as though it was a live node.
My solution is the following:
var illness = document.querySelectorAll('#illness')[0];
var fieldset = document.querySelectorAll('#illness > fieldset')[0];
var dupe = fieldset.cloneNode(true);
function duplicate() {
illness.appendChild(dupe.cloneNode(true));
}
This works, but I would appreciate some enlightenment on why the first did not – it is not clear from the documentation for querySelectorAll or cloneNode that cloneNode shouldn’t be expected to clone the non-live node obtained initially in fieldset
.