innerHTML vs appendChild()

Which approach is better?

Marian C.
9 min readMar 14, 2021

Both innerHTML property and appendChild() method can be used to add new contents to the page.

Differences between innerHTML and appendChild()

Verbosity

innerHTML is supposed to by assigned a HTML string, whereas appendChild() accepts only Node objects.

When innerHTML property of an HTML element is assigned an HTML, the browser parses the string into nodes and then replaces the children of the parent element with the created nodes. innerHTML is easy to use and the code with innerHTML is maximally concise.

el.innerHTML='<div title="Some title">Some text</div>';

In contrast, appendChild() does not accept HTML and needs extra code for generating the Node objects.

const cell = document.createElement("div");
cell.title = "Some title";
cell.appendChild(document.createTextNode("Some text"));
el.appendChild(cell);

However, when elements with many attributes such as inputs need to be inserted into a page, the code is more legible and concise if appendChild() is used. For example a simple helper function input(props) can be used to easily create inputs of any type:

function input({ list, ...props }) {…

--

--

Marian C.
Marian C.

Written by Marian C.

Java, JavaScript and SQL developer. Interested in data collection and visualization.