Solve - getElementById is not a function Error in JS


Borislav Hadzhiev

Tue Oct 19 20211 min read


Photo by Kelly Sikkema

Solve - getElementById is not a function Error #

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

  1. Misspelling the getElementById method - note that the method 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.

// โ›”๏ธ 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.

Since there can only be a single element on the page with the particular ID, it doesn't make sense for the method to be scoped to a particular element and it 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 use the method on the document object, e.g. document.getElementById('btn').

<!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 in our JavaScript code we are able to call the getElementById method on the document object.

// โœ… Works const btn = document.getElementById('btn'); console.log(btn); // ๐Ÿ‘‰๏ธ button#btn

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

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