Perhaps I am misunderstanding this example, but I had what appears to be the misconception that querying the DOM could be relatively rather slow and was looking for a "good" way to remove all selections from a variable-sized list.
The thought was that if a reference was held in memory to the children collection of a parent node, it would quicker to iterate the children and remove the selection (method_2) class than it would be to use querySelectorAll to iterate/traverse the DOM to locate selected children and then iterate that collection to remove the selection class (method_1).
However, that appears to be incorrect. Why is this the case? Or did I make a mistake?
Is the native method of querySelectorAll that much faster than a JS script loop?
Thank you.
let
p = document.querySelector('.parent'),
f = document.createDocumentFragment(),
c = p.children
;
function populate(n,mod) {
for (let d, i =0; i < n; i++) {
d = document.createElement("DIV");
if ( i % mod === 0 ) d.className = "sel";
f.append(d);
}
p.append(f);
console.log(`populated total of ${n} having ${p.querySelectorAll('.sel').length} selected.`);
}
function method_1() {
let n = Date.now();
p.querySelectorAll('.sel').forEach( v => v.classList.remove('sel'));
console.log(`method_1 elapsed: ${Date.now() - n}`);
}
function method_2() {
let
n = Date.now(),
i,
l = c.length
;
for (i =0; i < l; i++) {
c[i].classList.remove('sel');
}
console.log(`method_2 elapsed: ${Date.now() - n}`);
}
populate(100000,250);
method_1()
console.log(`Remaining selected after method_1: ${p.querySelectorAll('.sel').length} selected.`);
populate(100000,250);
method_2();
console.log(`Remaining selected after method_2: ${p.querySelectorAll('.sel').length} selected.`);
<div class="parent"></div>
My results are similar to:
populated total of 100000 having 400 selected.
method_1 elapsed: 1
Remaining selected after method_1: 0 selected.
populated total of 100000 having 400 selected.
method_2 elapsed: 84
Remaining selected after method_2: 0 selected.
querySelectorAll
NodeList. No live updating.node.children
classList.remove) costs more in JS engine timeIn Short
querySelectorAll whenever you only need to touch elements that match a selector.children (or a JS loop) when you must inspect or transform every child, regardless of class.If your goal is "remove .sel from everything," querySelectorAll is simpler.
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