document.getElementsByTagName
returned me a NodeList object.
I would like to remove some items (let's say I would like to remove the first item from the NodeList)
Is there a way to do it? (I'm aware that I could manually copy all the nodes into an array but I do not wish to do that if NodeList by itself already has functions for us to remove elements in it)
I am aware that removing items from a NodeList has No Effect on the display (and should not cause any browser-display-refresh or stuff like that, I simply do not wish that NodeList object to hold a referennce to that Node)
is there a way to do it? (Or am i forced to copy all the items in the NodeList into an array?)
The Difference Between an HTMLCollection and a NodeListBoth are array-like collections (lists) of nodes (elements) extracted from a document. The nodes can be accessed by index numbers. The index starts at 0. Both have a length property that returns the number of elements in the list (collection).
Note: Although NodeList is not an Array , it is possible to iterate over it with forEach() .
In modern JavaScript, the simplest and easiest way to convert a NodeList object to an array is by using the Array. from() method: // create a `NodeList` object const divs = document. querySelectorAll('div'); // convert `NodeList` to an array const divsArr = Array.
As you can see in the specification, there is no method to remove an element from the list.
It would not make sense anyway. This NodeList
is live, meaning the DOM is searched again whenever you access a certain property, e.g. the length
. From MDC:
(...) The returned list lis live, meaning that it updates itself with the DOM tree automatically. (...)
So you have to copy the nodes into an array.
You can do this quite easily though by using Array
methods. E.g. to copy it and directly remove the first element:
var nodes = [].slice.call(elements, 1);
The NodeList
is an array-like object. Hence we can apply array functions to it, by using call
[docs]. [].slice
is just a shorthand to get a reference to the slice
[docs] method.
Just have the same use case as you.
For ES6 you can do this:
const myNodeList = ele.childNodes;
const [head, ...tail] = myNodeList;
console.log('the first item: ', head);
console.log('the remaining items: ', tail);
JavaScript ES6— The Spread Syntax (…)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With