JavaScript

TypeError: innerHTML is not a Function in JavaScript

For displaying HTML content in JavaScript, the “innerHTML” property is used. It can be utilized as “element.innerHTML = text”. If you try to use the innerHTML as a function, such as “innerHTML(text)”, you will encounter an error stating that “innerHTML is not a function in JavaScript” because innerHTML is a property, not a function.

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”:

<p id="time"></p>

In <script> tag or a JavaScript file, first, create a Date object using the Date constructor:

const date = new Date();

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:

document.getElementById("time").innerHTML(date.toLocaleTimeString());

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:

document.getElementById("time").innerHTML = date.toLocaleTimeString();

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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.