document.getElementByTagName is not a function in JavaScript
In this tutorial, we are going to learn about how to solve the TypeError:document.getElementByTagName is not a function in JavaScript.
The TypeError: “document.getElementByTagName 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.getElementsByTagName()
instead of document.getElementByTagName()
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.getElementByTagName()
method.
const elements = document.getElementByTagName("div");
// it gives error document.getElementByTagName is not a function
console.log(elements);
It gives a error document.getElementByTagName
is not a function, because we misspelled the getElementByTagName()
that should be getElementsByTagName()
To fix the above error, use the document.getElementsByTagName().
const elements = document.getElementsByTagName("div");
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.getElementsByTagName("div");
[...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.getElementByTagName 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.getElementsByTagName()
instead of document.getElementByClass()
method.