1

We have one ul element with four li child element contained within then lets say the following code is executed in the 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

What's wrong here?

user5680735
  • 703
  • 2
  • 7
  • 21
Jake
  • 244
  • 2
  • 16
  • 2
    `a.childNodes` does not return an array but `array-like` object... – Rayon Jul 31 '16 at 16:04
  • 3
    Use [__`Array.from`__](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from) over `array-like` collection. __Or__ [`[].slice.call`](http://stackoverflow.com/questions/2125714/explanation-of-slice-call-in-javascript) could be used as well! – Rayon Jul 31 '16 at 16:04

1 Answers1

2

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 = [].slice.call(a);
//now call the splice method.
nodesArray.childNodes.splice(1, 2, "abc", "cde");
naveen
  • 53,448
  • 46
  • 161
  • 251