<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
document.querySelectorAll(".test").forEach(function (el) { el.remove() })
Array.from(document.getElementsByClassName(".test")).forEach(function (el) { el.remove() })
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelectorAll | |
getElementsByClassName |
Test name | Executions per second |
---|---|
querySelectorAll | 1114925.6 Ops/sec |
getElementsByClassName | 1116432.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The provided benchmark compares two approaches to remove all elements with a specific class from an HTML document using JavaScript:
querySelectorAll
(using the DOM query API)getElementsByClassName
(using the DOM method)Options Compared
The two options being compared are:
Pros and Cons of Each Approach
Pros:
Cons:
Pros:
Cons:
Library and Purpose
In this benchmark, Array.from()
is used to convert the HTMLCollection returned by getElementsByClassName
into an array-like object that can be iterated over. The purpose of using Array.from()
is to provide a more modern and efficient way to iterate over the elements.
Special JS Feature or Syntax
There are no special JavaScript features or syntax used in this benchmark beyond what's standard for DOM manipulation.
Other Considerations
Other Alternatives
If you're looking for alternative approaches to remove elements from an HTML document, consider:
querySelector
(similar to QuerySelectorAll but returns a single element instead of an HTMLCollection).forEach
on the document body or a container element to iterate over all elements.Keep in mind that each approach has its pros and cons, and the choice ultimately depends on your specific use case and requirements.