[Solved] - document.getElementByClass is not a function in JavaScript
In this tutorial, we are going to learn about how to solve the TypeError:document.getElementByClass is not a function in JavaScript.
The TypeError: “document.getElementByClass is not a function” error occurs when use a incorrect method name in our JavaScript code.
To fix the error, use the correct method name that is document.getElementsByClassName()
instead of document.getElementByClass()
and makesure call on a vaid HTML elements.
Let’s see a example of how the error occurs and how to fix it:
<div class="row">Data 1</div>
<div class="row">Data 2</div>
<div class="row">Data 3</div>
Now, we need to access the three divs in JavaScript using the document.getElementsByClass()
method.
const elements = document.getElementByClass("row");
// it gives error document.getElementByClass is not a function
console.log(elements);
To fix the above error use the document.getElementsByClassName().
const elements = document.getElementsByClassName("row");
console.log(elements);
Output:
HTMLCollection(3) [div.row, div.row, div.row]
It returns a html collection of three divs.
We can also loop through the divs
by first converting the HTML collection into array and we can loop it using the forEach() method.
const elements = document.getElementsByClassName("row");
[...elements].forEach(el => console.log(el));
In the example above, we first converted the HTML collection to array using the spread operator then we used the forEach method to loop through the each element.
Conclusion
The TypeError: “document.getElementByClass is not a function” error occurs when use a incorrect method name in our JavaScript code.
To fix the error, use the correct method name document.getElementsByClassName()
instead of document.getElementByClass()
method.