33
Recently I’m creating a lot of HTML dynamically.
Example
var table = document.createElement('table');
table.style = 'width:500px;border:1px solid #CCC;';
var tbody = document.createElement('tbody');
for(let i = 0; i < 10; i++){
let tr = document.createElement('tr');
// 1
let td = document.createElement('td');
td.style = 'width:100px;border:1px solid #CCC;';
let span = document.createElement('span');
span.innerHTML = 'teste '+(i+1);
td.appendChild(span);
tr.appendChild(td);
// 2
td = document.createElement('td');
td.style = 'border:1px solid #CCC;';
span = document.createElement('span');
span.innerHTML = 'texto '+(i+1);
td.appendChild(span);
tr.appendChild(td);
tbody.appendChild(tr);
}
table.appendChild(tbody);
document.body.appendChild(table);
Doubt
Seeing some questions about JS I saw that in the vast majority the staff mounts by String
var html = '<table style="width:500px; border:1px solid #ccc">';
html += '<tbody>';
for(let i = 0; i < 10; i++){
html += '<tr>';
html += '<td style="width:100px;border:1px solid #CCC;">';
html += '<span>teste '+(i+1)+'</span>';
html += '</td>';
html += '<td style="border:1px solid #CCC;">';
html += '<span>texto '+(i+1)+'</span>';
html += '</td>';
html += '</tr>';
}
html += '</tbody>';
html += '</table>';
document.body.innerHTML += html;
- What are the differences between these methods? (apart from the fact of a being by Object and the other String)
- Are any of them better than the other, or are they equivalent? (except "I prefer thus...")
Tip: If you’re really writing a lot of dynamic HTML, the approach is wrong, because you’re spending time and possibly introducing bugs doing something that other people have already thought about. It would be better to use a template library or a framework such as Angular or React, the important thing being to separate the data from the rendering logic application.
– utluiz