Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the JavaScript NodeList immutable?

Recently I came across the fact that the childNodes property of an element returns a NodeList and not an Array. Now I understand that a NodeList is meant to be a live collection of elements, but I don't get why that precludes it having methods like indexOf, or even push.

Could anyone explain why the only thing you can do with a NodeList is index it?

like image 843
geekchic Avatar asked May 25 '26 07:05

geekchic


1 Answers

Because that's the way it's specified. The DOM API was designed separately from JavaScript. The fact that NodeList has some common aspects with JavaScript arrays (length and indexing) is just...well, it's probably not actually a coincidence, but a by-product of inputs into the design process. Remember that JavaScript is not the only language that has DOM bindings.

You can readily affect the contents of a NodeList using the DOM API:

  • DOM2 Core
  • DOM2 HTML
  • DOM3 Core

...or of course, your favorite JavaScript library.

like image 117
T.J. Crowder Avatar answered May 26 '26 20:05

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!