coasterrel
coasterrel

Reputation: 113

Does remove() remove Nodes from a Nodelist which got created by 'querySelectorAll'?

I am new to programming and have difficulties to understand following in Javascript:

My code:

let nodeList = document.getElementById('ID').querySelectorAll('img');
    for (i=0; i < nodeList.length; i++) {
        nodeList[i].remove();
    }

This code removes all referenced 'img'-elements from my HTML but no elements are removed from my 'nodeList'.

Why remove() only removes from the HTML but not remove the 'nodeList'-elements and is there a way to remove the elements from display & from the nodeList?

Thank You

Upvotes: 3

Views: 3893

Answers (3)

Reidenshi
Reidenshi

Reputation: 300

Function that you are using -

remove()

Is working with DOM, and removes elements directly from there. If you want to remove also from nodeList array - then you need to use splice() func The final code will looks like -

let nodeList = document.getElementById('ID').querySelectorAll('img');
for (i=0; i < nodeList.length; i++) {
    nodeList[i].remove();
    nodeList.splice(i,1)
}

Upvotes: -1

Alex Brohshtut
Alex Brohshtut

Reputation: 2060

You get your nodeList from nodes that are present on DOM.
Then you remove it from the DOM. If you now will run the same query - you will get a new list without these nodes.
As explained here https://stackoverflow.com/a/6545450/3125477 you can't directly remove elements from NodeList.

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36564

This is because querySelectorAll() returns the static list of the elements. Meaning that the list will keep the reference to the element even its removed. It doesn't change after being assigned.

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors

On the other hand if you want live collection you can use document.getElementsByTagName(),document.getElementsByClassName() etc

const divs = document.getElementsByTagName('div');
divs[1].remove();
console.log(divs)
<div>Hey</div>
<div>H</div>
<div>B</div>

Upvotes: 2

Related Questions