Reputation: 1816
How can I remove one NodeList from another? For example, if I have:
var all = document.querySelectorAll('*');
var divs = document.querySelectorAll('div');
var removed = all - divs;
This doesn't work however. What is the correct method for doing this with the result being a nodelist and not an array?
Upvotes: 0
Views: 811
Reputation: 707238
You can turn the all
nodeList
into an array and then use array methods to do searching and removals:
var all = Array.prototype.slice.call(document.querySelectorAll('*'), 0);
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
var pos = all.indexOf(divs[i]);
if (pos !== -1) {
all.splice(pos, 1);
}
}
This requires IE9 (for .indexOf()
) or you can use a polyfill to make it work in older versions of IE or you can make your own function that iterates through an array to find if an element matches.
On second thought, there's a bit of an easier way to do this:
var all = Array.prototype.slice.call(document.querySelectorAll('*'), 0);
for (var i = all.length - 1; i >= 0; i--) {
if (all[i].tagName === "DIV") {
all.splice(i, 1);
}
}
Upvotes: 2
Reputation: 3327
var all = document.querySelectorAll('*');
var divs = document.querySelectorAll('div');
var removed = all.filter(function(i){
return divs.indexOf(i) < 0;
});
Upvotes: -1