Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Alexandre Croussette
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'
.
Here is an example of how the error occurs.
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.
<!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.
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.
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.
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.
// 👇️ <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 elementafterbegin
- insert inside of the element, before its first childbeforeend
- insert inside the element, after its last childafterend
- insert after the element