<ul><li class="nolink"><a href="#" rel="next">A link with class .nolink</a></li><li class="nolink"><a href="#" rel="next">Another link with class .nolink</a></li><li><a href="#" rel="next">A link with no classes</a></li></ul>
const noLinks = document.getElementsByClassName('nolink');
Array.prototype.forEach.call(noLinks, function(noLink) {
const matches = noLink.getElementsByTagName('a')[0];
matches.setAttribute('role', 'link');
matches.setAttribute('aria-disabled', 'true');
matches.removeAttribute('href');
matches.removeAttribute('rel');
});
document
.querySelectorAll('.nolink a')
.forEach(noLink => {
noLink.setAttribute('role', 'link');
noLink.setAttribute('aria-disabled', 'true');
noLink.removeAttribute('href');
noLink.removeAttribute('rel');
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.forEach | |
querySelectorAll |
Test name | Executions per second |
---|---|
Array.prototype.forEach | 269440.0 Ops/sec |
querySelectorAll | 214985.6 Ops/sec |
What is being tested?
MeasureThat.net is testing two approaches for iterating over HTML elements: Array.prototype.forEach
and querySelectorAll
. Both methods are used to iterate over the <ul>
element with class nolink
, which contains three links.
Options compared:
The benchmark compares the performance of:
Array.prototype.forEach
: This method takes an array-like object (in this case, a NodeList) and calls a callback function on each element in the collection.querySelectorAll
: This method returns a NodeList that contains all elements that match the specified CSS selector ('.nolink a'
) in the given HTML document.Pros and Cons of each approach:
Array.prototype.forEach
:Array.prototype.slice()
or Array.from()
) if you need to use array methods.querySelectorAll
:Libraries and features:
Neither Array.prototype.forEach
nor querySelectorAll
rely on specific libraries. However, they do use:
querySelectorAll
method uses a CSS selector ('.nolink a'
) to find the relevant elements.Special JS features or syntax:
There are no specific JavaScript features or syntax that require special handling in this benchmark. Both methods use standard JavaScript concepts and libraries (DOM).
Other alternatives:
If you need to iterate over HTML elements, other alternatives might include:
document.addEventListener('DOMContentLoaded', () => { ... });
: This method can be used to wait for the DOM to be fully loaded before executing code.const elements = document.querySelectorAll('.nolink a');
: While querySelectorAll
is already tested, using document.querySelectorAll
with a CSS selector might provide different results due to caching and performance optimization.Keep in mind that these alternatives may not be directly comparable to the original benchmark, as they may have different performance characteristics or use cases.