Fix - document.getElementsByClass is not a Function in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Fix - document.getElementsByClass is not a Function #

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee