Dan Bray Dan Bray -4 years ago 59
Javascript Question

Remove nodes from a form?

I am trying to remove (almost) all nodes from a form. I managed to remove all nodes from the form using the following code:

var form;
form = document.getElementById(id);
while (form.hasChildNodes())
form.removeChild(form.lastChild);


However, that will not suffice because I will be adding some logic to keep certain nodes. Therefore, I need to remove the nodes using a
for loop
. I tried with the following code:

var form, formNodes, totalNodes, i;
form = document.getElementById(id);
formNodes = form.childNodes;
totalNodes = formNodes.length;
for (i = 0; i < totalNodes; i++)
form.removeChild(formNodes[i]);


Some nodes are removed, but I received this error:


Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'


Considering
formNodes
only contains nodes, what could be causing the error? Any help would be greatly appreciated.

EDIT

I tried looping backwards using the following code:

var form, formNodes, totalNodes, i;
form = document.getElementById(id);
formNodes = form.childNodes;
totalNodes = formNodes.length;
for (i = totalNodes - 1; i >= 0; i--)
form.removeChild(formNodes[i]);


And it removes all nodes. I'll subtract an offset variable from
i
so that I am able to keep certain nodes.

Answer Source

The childNodes property updates as you remove children.

Therefore, once you remove half of the children, your index will be past the end of the updated NodeList.

You should either loop backwards (so that the indices never adjust) or copy to an array in advance. Or just keep deleting the first child until the NodeList is empty.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download