<div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div> <div class="div1"><span>stuff</span><span>stuff</span><span>stuff</span><span>stuff</span><span>stuff</span><span>stuff</span><span>stuff</span><span>stuff</span><span>stuff</span><h1>H1</h1><span>stuff</span><span>stuff</span><span>stuff</span><span>stuff</span><span>stuff</span><span>stuff</span><h2>h2</h2></div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div><div>stuff</div>
document.getElementsByClassName("div1")
document.querySelector(".div1")
$.find('.div1')
$('.div1')
$(document.getElementsByClassName("div1"))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementsByClassName | |
querySelector | |
speed find | |
selector | |
j |
Test name | Executions per second |
---|---|
getElementsByClassName | 3637227.2 Ops/sec |
querySelector | 320583.0 Ops/sec |
speed find | 1041159.3 Ops/sec |
selector | 605474.8 Ops/sec |
j | 344037.2 Ops/sec |
This benchmark compares different ways to select a specific HTML element within a webpage. It focuses on the performance of these selection methods.
Let's break down each test case:
getElementsByClassName("div1")
: This uses the built-in document.getElementsByClassName()
method to find all elements with the class "div1". This method returns a live HTMLCollection, which means it updates automatically if the DOM changes.
querySelector
when selecting single elements, as it creates a collection of all matching elements.document.querySelector(".div1")
: This uses the document.querySelector()
method to find the first element with the class "div1".
getElementsByClassName
for selecting single elements, as it stops searching once the first match is found. More versatile, as it can also select by ID, tag name, and more complex CSS selectors.querySelectorAll
.$.find('.div1')
: This uses jQuery's $.find()
method to select the first element with the class "div1".
$('.div1')
: This is another jQuery method for selecting the first element with the class "div1". It's generally equivalent to $.find('.div1')
.
$(document.getElementsByClassName("div1"))
: This combines jQuery with the native getElementsByClassName()
method. It selects all elements with the class "div1" using the native method and then wraps them in a jQuery object for additional manipulation options.
Other Alternatives:
While not explicitly tested here, there are other ways to select elements:
document.getElementById()
: Used for selecting elements by their unique ID attribute.
document.querySelectorAll()
: Similar to querySelector
, but returns a NodeList of all matching elements.
The benchmark results will show you which method performs best in terms of executions per second, giving you insight into the relative efficiency of each approach.