Is creating element and set innerHTML more efficient or add HTML directly?

Solution 1:

The most effective would be to use document.createElement because in addition to creating the element you have control of all its properties, that is, you don't need to use querySelector, just store the created element in a variable and then add it to the DOM, innerHTML reconstructs the entire DOM while appendChild only the part of the DOM where the parent element is, besides that you have no control over the element or its children.

const myElement = document.createElement("span");
myElement.textContent = "Hello world!";
myElement.className = "message";

document.body.appendChild(myElement);
body {
  text-align: center;
}

.message {
  font-weight: bold;
  font-size: 32px;
  color: #222;
}

"innerHTML += ..." vs "appendChild(txtNode)"

https://betterprogramming.pub/whats-best-innertext-vs-innerhtml-vs-textcontent-903ebc43a3fc