Skip to content Skip to sidebar Skip to footer

Why Document.queryselector Is More Efficient Than Element.queryselector

I did a test with few iterations to test efficiency of Document.querySelector and Element.querySelector. Markup:
Script: Q

Solution 1:

From my comment above, the selector takes into account the entire document, then filters the items to check if they are descendants of the target. So it's likely that it still needs to scan the entire DOM tree like document.querySelector would need to do.

There is a discussion of the issue (that is still the current behaviour) here. You'll see in the code sample below the span is included as a result, because it can't just query items below foo in isolation.

Fiddle

Code:

document.body.innerHTML = '<div><pid="foo"><span></span></p></div>';
var foo = document.getElementById('foo');
alert( foo.querySelectorAll('div span').length);

Post a Comment for "Why Document.queryselector Is More Efficient Than Element.queryselector"