This tutorial will discuss the mentioned error and its solution.
How Does “TypeError: innerHTML is not a function in JavaScript” occur?
When we try to invoke the innerHTML property as a function, we get the mentioned error. Let’s see an example of how this error is encountered.
Example
In the given example, we will show the current time on the web page using JavaScript. For this, first, create an element <p> in an HTML file by assigning id “time”:
In <script> tag or a JavaScript file, first, create a Date object using the Date constructor:
Then, get the reference of the HTML element where we will want to show time with the help of the “getElementById()” method and calls the “innerHTML” property as a function by passing the Date’s method “toLocaleTimeString()” which will show a time on the web page:
Executing the above code will not display time on the page and throw an error that will be shown in the “console” window:
Now, let’s see in the given section how to fix this error!
How to Fix the “innerHTML is not a function in JavaScript” Error?
To fix the above-discussed issue, set the innerHTML attribute of the relevant DOM element, such as “element.innerHTML = text”.
Example
Assign the value to the innerHTML property/attribute by getting the DOM element with the help of the “getElementById()” method by passing the element’s assigned id:
Output
That’s all about the innerHTML is not a function in JavaScript error and the solution.
Conclusion
The specified error occurs when you will try to invoke the innerHTML property as a function. To fix this issue, set the innerHTML attribute of the relevant DOM element, such as “element.innerHTML = text”. In this tutorial, we discussed the TypeError: innerHTML is not a function in JavaScript, how it occurs and how to fix it.