I was wondering difference between these two techniques used for creating HTML elements. I can't find any difference. I just want to know if there exists a difference or more on any basis (performance or whatever).
The 1st technique using JS inbuilt 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 2nd technique just in 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 two techniques produce the same result and I can easily manipulate each HTML element created in any of the two ways (and in the same way).
Fiddle1 using 1st technique
Fiddle2 using 2nd technique
See the above two fiddles, I've used the same code for manipulating the elements. As you'll see both produces the same output. Then what makes them different. 1st one took several lines while the 2nd one just 1 line. Any performance difference between them?? Or any other difference they have which I'm not noticing.
Correct me if I was wrong anywhere.
AND I know the 1st one preserves references to various objects which can be helpful later in the code but I'm not much after that. My main question is - difference between creating elements one by one, adding properties, etc. and the 2nd one which just do it in single step by using String.
Thanks.