Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we Directly remove Nodes from a NodeList?

Tags:

javascript

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?)

like image 617
user8490 Avatar asked Jul 01 '11 08:07

user8490


People also ask

What is the difference between node and NodeList?

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).

Can you loop through a NodeList?

Note: Although NodeList is not an Array , it is possible to iterate over it with forEach() .

How do I turn a NodeList into an array?

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.


2 Answers

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.

like image 100
Felix Kling Avatar answered Oct 16 '22 23:10

Felix Kling


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 (…)

like image 39
wk9876 Avatar answered Oct 17 '22 01:10

wk9876