Solve - getElementById is not a function Error in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Solve - getElementById is not a function Error #

The "getElementById is not a function" error occurs for 2 reasons:

  1. Misspelling the getElementById method (the name is case-sensitive)
  2. Using the getElementById method on an element instead of the document object.

typeerror getelementbyid is not a function

Here are examples of how the error occurs.

index.js
// ⛔️ notice capital D in id, should be getElementById const btn = document.getElementByID('btn'); // ⛔️ using method on another element instead of document btn.getElementById('test');

The first example misspells the getElementById method which causes the error.

The second example calls the getElementById method on an element that's not the document object.

There can only be a single element on the page with a particular ID, so it doesn't make sense for the method to be scoped to a specific element. The method can only be used on the document object.

To solve the "getElementById is not a function" error, make sure to spell the getElementById() method correctly, as it is case-sensitive, and only call the method on the document object, e.g. document.getElementById('btn').

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- 👇️ button with `id` of `btn` --> <button id="btn">Click me</button> <!-- ✅ Your JS script here ✅ --> <script src="index.js"></script> </body> </html>

Now we are able to call the getElementById method on the document object.

index.js
// ✅ Works const btn = document.getElementById('btn'); console.log(btn); // 👉️ button#btn

We spelled the getElementById method correctly and called it on the document object, so everything worked as expected.

Use the search field on my Home Page to filter through my more than 3,000 articles.