I am trying to dynamically add elements created in JS to HTML, but would like to know the most efficient way of doing this. For example adding users to a list, the result would be:
<div id="user-list" style="display:flex; flex-direction:column">
<div id="user-1">
<span class="photo" style="width:25%">PHOTO</span>
<span class="name" style="width:25%">name</span>
<span class="surname" style="width:25%">surname</span>
<span class="age" style="width:25%">age</span>
</div>
<div id="user-2">
<span class="photo" style="width:25%">PHOTO</span>
<span class="name" style="width:25%">name</span>
<span class="surname" style="width:25%">surname</span>
<span class="age" style="width:25%">age</span>
</div>
</div>
I tried these 2 ways:
document.getElementById("user-list").innerHtml +=
`<div id="user-${userId}">
<span class="photo" style="width:25%">${userPhoto}</span>
<span class="name" style="width:25%">${userName}</span>
<span class="surname" style="width:25%">${userSurname}</span>
<span class="age" style="width:25%">${userAge}</span>
</div>`
and
var user = document.createElement("div");
user.id = `user-${userId}`
var photo = document.createElement("span");
photo.setAttribute('style','width:25%')
photo.innerHTML = userPhoto;
var name = document.createElement("span");
name.setAttribute('style','width:25%')
name.innerHTML = userName;
var surname = document.createElement("span");
surname.setAttribute('style','width:25%')
surname.innerHTML = userName;
var age = document.createElement("span");
age.setAttribute('style','width:25%')
age.innerHTML = userAge;
user.appendChild(photo);
user.appendChild(name);
user.appendChild(surname);
user.appendChild(age);
document.getElementById("user-list").appendChild(user);
And it would loop creating and adding all the users (for example 20 users).
Which would be more efficient?