What is the difference of an already 'created' element stored in a variable or creating it from scratch
var box = document.getElementById("set");
var bc1 = document.getElementById("bc1");
bc1.onclick = function() {
var div1 = "<div class='caja1'>Hola</div>";
box.innerHTML = div1;
}
// ELEMENTO CREADO DESDE CERO
var bc2 = document.getElementById("bc2");
bc2.onclick = function() {
var crear = document.createElement("div");
crear.innerHTML = "Hola 2";
crear.setAttribute("class", "caja2");
box.appendChild(crear);
}
<div id="set"></div>
<button id="bc1">Crear 1</button>
<button id="bc2">Crear 2</button>
As you have it, in the first option you replace the content of the div and only that element remains; while the second option allows you to add as many elements as you need, although you can have the same functionality with both.
In theory, adding elements with
innerHTML
is slower, because the browser must interpret the string to create objects and insert them, and itappendChild()
works directly with objects.Conclusion: If you are only going to replace the content of the div, it does not matter what you use, but if you are going to work with multiple elements, it is definitely convenient
appendChild()
that it allows you more flexibility, such as assigning attributes more easily, as an example: