Andrew Andrew - 1 year ago 68
Javascript Question

Strange behaviour of splice method in the context of childnodes

For instance we have one ul element with four li child element contained within!
then lets say the following code is executed int he console

var a = document.getElementsByTagName("ul")[0];
a.childNodes.splice(1, 2, "abc", "cde");

Then the error pops up with the message:

TypeError: a.childNodes.splice is not a function

Whats wrong here??

Answer Source

Node.childnodes returns a Node List which is not an array in JavaScript. So you cannot apply splice to it.

As MDN notes,

Why is NodeList not an Array?

NodeList are used very much like arrays and it's tempting to invoke Array.prototype methods on them, however NodeList objects don't have any of the familiar Array methods.

A work around will be to make it an array like this.

var nodesArray = [];
//now call the splice method.
nodesArray.childNodes.splice(1, 2, "abc", "cde");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download