<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="el"></div>
document.getElementById("el").classList.remove("test");
$("#el").addClass("test");
$("#el")[0].classList.add("test");
document.querySelector("#el").classList.add("test");
document.getElementById("el").classList.add("test");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery addClass | |
jQuery classList.add | |
querySelector classList.add | |
getElementById classList.add |
Test name | Executions per second |
---|---|
jQuery addClass | 459264.4 Ops/sec |
jQuery classList.add | 753642.2 Ops/sec |
querySelector classList.add | 1155388.9 Ops/sec |
getElementById classList.add | 1588467.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and the pros/cons of each approach.
Benchmark Overview
The benchmark measures the performance difference between four different ways to add a class to an HTML element:
addClass
methodclassList.add
method (with $()
notation)querySelector
with classList.add
getElementById
with classList.add
Comparison
The benchmark compares the performance of these four approaches in Chrome 78 on a Windows 7 desktop.
Here's a brief overview of each approach:
addClass
method: This is a simple method that adds a class to an element without removing any existing classes. It's widely used in web development but can lead to issues if not used carefully.classList.add
method (with $()
notation): This method uses the classList
property of the element and adds a new class to it. The $()
notation is used to select the element, which can be slower than using querySelector
.querySelector
with classList.add
: This approach uses the querySelector
API to select an element by its CSS selector and then calls classList.add
on that element.getElementById
with classList.add
: This approach uses the getElementById
method to retrieve an element by its ID and then calls classList.add
on that element.Pros/Cons of each approach
Here's a brief summary:
addClass
method:classList.add
method (with $()
notation):addClass
, faster performancequerySelector
with classList.add
:getElementById
with classList.add
:Library usage
The benchmark uses jQuery library to provide the addClass
and classList.add
methods. The querySelector
method is a native API in modern browsers.
Special JS features/syntax
None of the test cases use special JavaScript features or syntax beyond what's standard for modern web development (e.g., no async/await, no let/catch).