<!-- article out start -->
<article>
<!-- article in start -->
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque, nostrum.</p>
<!-- article in end -->
</article>
<!-- article out end -->
<!-- article out start -->
<article>
<!-- article in start -->
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque, nostrum.</p>
<!-- article in end -->
</article>
<!-- article out end -->
<!-- article out start -->
<article>
<!-- article in start -->
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque, nostrum.</p>
<!-- article in end -->
</article>
<!-- article out end -->
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT
);
const list = [];
for(let element; element; element = treeWalker.nextNode()) {
list.push(element);
}
const list = document.body.querySelectorAll('*');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
TreeWalker | |
querySelectorAll |
Test name | Executions per second |
---|---|
TreeWalker | 1894865.8 Ops/sec |
querySelectorAll | 710688.9 Ops/sec |
What is tested on the provided JSON?
The benchmark tests two different ways to iterate over HTML elements in JavaScript: using TreeWalker
and querySelectorAll(* )
.
Options compared:
TreeWalker
) to traverse the DOM tree and select only element nodes (NodeFilter.SHOW_ELEMENT
). It's a more explicit way to iterate over elements, but might be slower due to the overhead of creating a new walker.querySelectorAll
method with a wildcard selector (*
) to select all HTML elements on the page. It's a more concise and often faster way to get an array of element nodes.Pros and Cons:
Library:
TreeWalker
.Special JS feature/syntax:
None mentioned in the provided code.
Other considerations:
When choosing between these two options, consider the specific requirements of your project:
TreeWalker
might be a better choice.querySelectorAll(* )
is likely a better option.Other alternatives:
In addition to these two options, there are other ways to iterate over HTML elements in JavaScript:
forEach()
but provides more flexibility and control.These alternatives might be useful in specific scenarios, but they're not directly comparable to TreeWalker
and querySelectorAll(* )
in terms of performance or code conciseness.