document.getElementsByClass is not a Function in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 19, 2021

banner

Photo from Unsplash

document.getElementsByClass is not a Function in JavaScript #

The "document.getElementsByClass is not a function" error occurs when we misspell the getElementsByClassName method as it is case sensitive. To solve the error make sure to spell the method correctly when invoking it, e.g. document.getElementsByClassName('box').

document getelementbyclass is not a function

Here's an example of how the error occurs and how to solve it.

index.js
// ⛔️ TypeError: document.getElementsByClass is not a function const boxes = document.getElementsByClass('box'); // ✅ Works const boxes = document.getElementsByClassName('box'); console.log(boxes); // 👉️ [div.box, div.box, div.box]

The html for the page contains 3 div elements with a class name of box.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <script src="index.js"></script> </body> </html>

What's important in the example is the spelling of the getElementsByClassName as the method is case-sensitive.

A common mistake is to forget the s (notice that Elements is plural).

The method returns an array-like object that contains the elements with the provided class name, which you can access using a specific index or iterate over.

index.js
const boxes = document.getElementsByClassName('box'); // console.log(boxes); // 👉️ [div.box, div.box, div.box] // 👇️ get first div console.log(boxes[0]); // 👉️ div.box // 👇️ iterate over the array-like object of div elements for (const box of boxes) { console.log(box); }

The call to the console.log function shows how to access the first div element in the array-like object.

If you need to iterate over the elements, use the for...of loop.

Note that the getElementsByClassName method does not return a native JavaScript array, it returns an array-like object, so you can't use some of the array methods on it, e.g. forEach.

Conclusion #

The "document.getElementsByClass is not a function" error occurs when we misspell the getElementsByClassName method as it is case sensitive. To solve the error make sure to spell the method correctly when invoking it, e.g. document.getElementsByClassName('box').

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.