<div class="testClass"></div>
var el = document.getElementsByClassName('testClass')[0];
var className = el.className;
var el = document.querySelector('.testClass');
var className = el.className;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementByClassName | |
querySelector |
Test name | Executions per second |
---|---|
getElementByClassName | 3018389.2 Ops/sec |
querySelector | 3386053.2 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Overview
The benchmark compares the performance of two approaches to retrieve an HTML element by its class name:
document.getElementsByClassName('testClass')[0]
document.querySelector('.testClass')
Library and Purpose
In both test cases, a library (BOM: Browser Object Model) is being used, which provides a set of APIs to interact with the web browser.
The specific libraries used are:
document
: an object that represents the document element in the HTML document.getElementsByClassName
and querySelector
: methods of the document
object that allow you to retrieve elements by their class name or selector, respectively.Options Compared
Two options are being compared:
getElementsByClassName
: This method returns a live HTMLCollection object containing all elements with the specified class name(s). It's an older API that was widely supported in older browsers.querySelector
: This method returns the first element that matches the specified selector. It's a more modern and flexible API that allows for more powerful selectors.Pros and Cons
Here are some pros and cons of each approach:
getElementsByClassName
:querySelector
, as it needs to iterate over all elements with the class name(s).querySelector
:Special JS Feature or Syntax
Neither of these test cases uses any special JavaScript features or syntax. They are simple, straightforward examples that illustrate the performance difference between two DOM manipulation methods.
Other Alternatives
Other alternatives to getElementsByClassName
and querySelector
include:
document.querySelector
: document.querySelector('.testClass')
$('.testClass')[0]
However, these alternative approaches are not being tested in this benchmark.
I hope this explanation helps!