<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");
document.getElementById("el").classList.add("test");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery addClass | |
Javascript classList.add |
Test name | Executions per second |
---|---|
jQuery addClass | 1559404.0 Ops/sec |
Javascript classList.add | 4234068.0 Ops/sec |
Let's dive into the world of JavaScript benchmarks on MeasureThat.net.
Benchmark Overview
The benchmark compares two approaches to adding a class to an HTML element: jQuery's addClass
method and the native classList.add
method in modern JavaScript (ES6+).
Options Compared
There are only two options being compared:
addClass
: This method is part of the popular jQuery library, which provides a simplified way to manipulate HTML elements.classList.add
: This method is part of the native JavaScript API and allows direct access to an element's class list.Pros and Cons
addClass
:classList.add
:Other Considerations
The benchmark assumes that the test element (<div id="el">
) has an existing class named "test" that will be removed before running each test. This is because both approaches need to add a new class to the element.
Library: jQuery
jQuery is a popular JavaScript library that simplifies HTML element manipulation. The addClass
method adds a single class to an element, whereas the native classList.add
method can add multiple classes at once.
Special JS Feature/Syntax
There's no special feature or syntax used in this benchmark, but it's worth noting that the classList
API is a modern feature introduced in ES6+ JavaScript. If you need to support older browsers, you might need to use a polyfill or fallback approach.
Alternative Approaches
If you're looking for alternative approaches to adding classes to elements, here are a few:
style
property: You can use the style
property to set the className
property directly.document.getElementById("el").style.className = "test";
class-list
that provide an easy way to work with class lists in older browsers.classList.add
method using DOM manipulation or other techniques.Keep in mind that each approach has its pros and cons, and the best choice depends on your specific use case and requirements.