The error “TypeError: getElementById is not a function” happens for two common reasons (Based on StackOverflow users):
- The capitalization of “Id” isn’t correct
getElementById()on an element instead of the
Here’s what this error looks like in the browser’s console:
Psssst! Do you want to learn web development in 2023?
How to fix the “TypeError: getElementById is not a function” error
Before anything, let’s have a refresher from the MDN Docs:
getElementById()method returns an Element object representing the element whose id property matches the specified string.
As mentioned earlier, either the capitalization of ID is incorrect, or you’re calling this method on an element other than the
If the capitalization of “Id” isn’t correct: Simply put, it’s
getElementbyId() and not
getElementbyID() – Note the capitalized D.
Since we use ID as an abbreviation for identifier or identity document, it might feel natural to write it all in caps. But in the case of
getDocumentById(), it has to be
Id (with lowercase
// ⛔ Incorrect const element = document.getElementByID('id-string') // Raises Uncaught TypeError: getElementById is not a function
Here's the correct form:
// ✅ Correct const element = document.getElementById('id-string')
getElementById() is called on an element rather than the document object: Unlike other element locators like
querySelector() - that are available on Element objects - The
getElementById() function is only available as a method of the
The reason is ID values are supposed to be unique throughout the document, and there is no need for "local" versions of
Let's suppose this is our HTML document:
<!doctype html> <html> <head> <title>Testing document.getElementbyId()</title> </head> <body> <section id=container> <button id=button></button> </section> </body> </html>
To get the button element:
// ✅ Correct form: const containerElement = document.getElementById('container') const buttonElement = document.getElementByID('button') // ⛔ But this raises the TypeError: getElementById is not a function error buttonElement = containerElement.getElementByID('button')
Please note the ID string we pass to the function is also case-sensitive. So if the result of
null, you might want to double check the ID string.
Here's an example:
// ⚠️ returns null since the ID is button not Button const button = document.getElementById('Button') // ✅ This is correct button = document.getElementById('button')
Alright, I think that does it. If you use the "TypeError: getElementById is not a function" in your Vue or React project, the solution would be the same.
I hope this quick guide helped you fix your problem.
Thanks for reading.
Never miss a guide like this!
Disclaimer: This post may contain affiliate links. I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.