I am curious about the distinction between these two methods for creating HTML elements. I cannot seem to find any difference. I simply want to understand if there are any variations based on performance or any other factors.
The first technique involves using built-in JS methods -
var el1 = document.createElement('div');
el1.innerHTML = 'Element Div 1';
var el2 = document.createElement('span');
el2.innerHTML = ' - Span Element';
el2.classList.add('red');
document.body.appendChild(el1);
el1.appendChild(el2);
el1.id = "div";
.red {
color: red;
font-size: 13px;
}
#div {
font-size: 18px;
color: burlywood;
}
Now the second technique, in just one step -
document.body.innerHTML = '<div id="div">Element Div 1<span class="red"> - Span Element</span></div>';
.red {
color: red;
font-size: 13px;
}
#div {
font-size: 18px;
color: burlywood;
}
Both of these techniques yield the same outcome and I can easily manipulate each HTML element created in either way.
View Fiddle1 using the first technique
View Fiddle2 using the second technique
Upon observing the two fiddles above, I notice that both methods produce identical outputs. However, the first method requires multiple lines while the second method accomplishes the task in a single line. Is there any performance disparity between them? Any other differences that I may be overlooking?
Feel free to correct me if I am mistaken anywhere.
I acknowledge that the first method retains references to different objects, which can be beneficial later in the code. Nevertheless, my primary inquiry pertains to the difference between creating elements individually with properties versus the second method, which achieves the same result in a single step using strings.
Thank you.