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 th
var MySet = { 0: {value: document.body, enumerable: true}, 1: {value: document.head, enumerable: true}, 2:{value: document.documentElement, enumerable: true}, length: {value: 3}};
var protoNodelist = document.createDocumentFragment().childNodes;
var MyNodelist = Object.create(protoNodelist, MySet);
MyNodelist; // Output: NodeList {0: body, 1: head, 2: html, length: 3}
removeNode(MyNodelist, 1); // Output: NodeList {0: body, 1: html, length: 2}
function removeNode(NodeList, i){
var newElementSet = {};
var newElementSeti = 0;
for(NodeListi = 0; NodeListi < NodeList.length; NodeListi++){
if(NodeListi != i){
newElementSet[newElementSeti] = {value: NodeList[NodeListi], enumerable: true};
newElementSeti += 1;
};
};
newElementSet['length'] = {value: newElementSeti};
var nodelist = document.createDocumentFragment().childNodes;
var newNodelist = Object.create(nodelist, newElementSet);
newNodelist.__proto__ = newNodelist.__proto__.__proto__;
return newNodelist;
};
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 (…)