Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between iterating node.children and node.querySelectorAll?

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.
like image 647
Gary Avatar asked Mar 15 '26 06:03

Gary


1 Answers

querySelectorAll

  • Uses highly optimized selector matching to collect only the elements
  • Returns a static NodeList. No live updating.

node.children

  • Returns a live HTMLCollection of every direct child
  • Your loop is pure JavaScript, so each iteration and method call (classList.remove) costs more in JS engine time

In Short

  • Use querySelectorAll whenever you only need to touch elements that match a selector.
  • Use 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.

like image 183
Abdulla Nilam Avatar answered Mar 16 '26 21:03

Abdulla Nilam