querySelector() VS getElementsByClassName()

Benchmark created on


Description

Using various methods to select the descendants of a parent element.

Preparation HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="parent">
    <div class="children-a"></div>
    <div class="children-b"></div>
    <div class="children-c"></div>
</div>

</body>
</html>

Test runner

Ready to run.

Testing in
TestOps/sec
1
const parent = document.getElementById("parent");
const childrenA = parent.querySelector(".children-a");
const childrenB = parent.querySelector(".children-b");
const childrenC = parent.querySelector(".children-c");
ready
2
const parent = document.getElementById("parent");
const childrenA = parent.getElementsByClassName("children-a")[0];
const childrenB = parent.getElementsByClassName("children-b")[0];
const childrenC = parent.getElementsByClassName("children-c")[0];
ready
3
const childrenA = document.querySelector("#parent .children-a");
const childrenB = document.querySelector("#parent .children-b");
const childrenC = document.querySelector("#parent .children-c");
ready
4
const childrenA = document.querySelector(".children-a");
const childrenB = document.querySelector(".children-b");
const childrenC = document.querySelector(".children-c");
ready
5
const childrenA = document.getElementsByClassName("children-a")[0];
const childrenB = document.getElementsByClassName("children-b")[0];
const childrenC = document.getElementsByClassName("children-c")[0];
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.