Don’t worry when you get an “TypeError: getElementById is not a function” in JavaScript. Let’s find out how to fix this error in this article.
Why does the error occur?
The most common mistake people make is the d character error. Correctly write ‘d’
, if you write ‘D’
you will get the following error. And the second error occurs when the get method is called on a DOM element instead of a document. If you write it wrong, you will get an error below:
Html code sample:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="text">Hello</div>
<script src="index.js"></script>
</body>
</html>
Code sample:
//Wrong character D
let text = document.getElementByID('text');
text.textContent = "Hello, Welcome to LearnshareIT";
//Wrong because the getElementById is called on an element
text.getElementById('text').textContent = "Hello, Welcome to LearnshareIT";
Output
Uncaught TypeError: document.getElementByID is not a function
How to fix the TypeError: getElementById is not a function in JavaScript?
Document.getElemetnById in JavaScript is a method of the DOM object, which works to get an element from the DOM through the id attribute value of that element.
The getElementById method will return the Element Object if an element with the specified id is found and will return null if no matching element is found.
The syntax to use the getElementById method in JavaScript is as follows:
document.getElementById(id)
Parameter
- id: the id attribute value of the element to get.
Code sample
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<p id ="p">This is a paragraph</p>
<script>
console.log(document.getElementById("p"));
</script>
</body>
</html>
Output
<p id="p">This is a paragraph</p>
Spell check and use document.getElementById
To fix that error, we must use Id instead of ID and call the method on the document object.
Code sample:
let text = document.getElementById('text');
text.textContent = "Hello, Welcome to LearnshareIT";
console.log(text);
Output
<div id="text">Hello, Welcome to LearnshareIT</div>
The error is fixed, and the method works properly if you use it properly.
Summary
Stay calm when you get the TypeError: getElementById is not a function in JavaScript, then check the syntax’s spelling and the object of the call to the method, and you will find out how to fix it. I hope they are helpful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about Javascript in the next lessons here. Have a great day!
Hi, my name is Joni Smith. My job is a programmer. I love learning programming languages, especially C++, C#, php, javascript, html, css. I want to share them with you. I hope my articles will bring a lot of useful knowledge to you.
Name of the university: HVNH BA
Major: htttql MIS
Programming Languages: C++, C#, php, javascript, html, css