Solve - innerHTML is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

Solve - innerHTML is not a function Error #

The "innerHTML is not a function" error occurs when we try to call the innerHTML property as a function. To solve the error, assign a value to the innerHTML property of the specific DOM element, e.g. element.innerHTML = 'example'.

typeerror innerhtml is not a function

Here is an example of how the error occurs.

index.js
const box = document.getElementById('box'); // โ›”๏ธ TypeError: innerHTML is not a function box.innerHTML('<h1>New Content</h1>');

We got access to a DOM element by using the getElementById method and tried to invoke the Element.innerHTML property as a function, which caused the error.

To solve the error, set a specific value to innerHTML property of the DOM element, without invoking it as a function.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box</div> <!-- โœ… Your JS script here โœ… --> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); // โœ… Works box.innerHTML = '<h1>New Content</h1>';

The innerHTML property sets the HTML markup contained within the specific DOM element.

Note that setting a new value on the innerHTML property replaces the contents of the element with the provided value.

If you're looking to read the HTML content of an element, you can access the innerHTML property without assigning a value to it.

index.js
const box = document.getElementById('box'); // ๐Ÿ‘‡๏ธ "<span>Box</span>" console.log(box.innerHTML);

If you are looking to add a DOM element, instead of replacing the current markup contained in an element, you can use a method like Element.insertAdjacentHTML.

index.js
// ๐Ÿ‘‡๏ธ <div id="box1">Box 1</div> const box1 = document.getElementById('box1'); box1.insertAdjacentHTML('afterend', `<div id="box2">Box 2</div>`); /** ๐Ÿ‘‡๏ธ Result * <div id="box1">Box 1</div> * <div id="box2">Box 2</div> */

The first parameter we passed to the insertAdjacentHTML method is the position we want to insert the HTML at.

There are 4 positions to pick from:

  • beforebegin - insert before the element
  • afterbegin - insert inside of the element, before its first child
  • beforeend - insert inside the element, after its last child
  • afterend - insert after the element

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