Create HTML element with Javascript (appendchild vs innerHTML)

Asked

Viewed 21,328 times

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...")
  • 9

    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.

3 answers

36


appendchild vs innerHTML

The appendChild does not cause a complete reconstruction of the DOM or even all the elements / nodes within the target.

The innerHTML cause a complete reconstruction of the content of the target element, which if you are attaching is unnecessary.

Consequently, if using innerHTML += content will do the re-parse of all HTML, a good practice could be the iteration in a variable to add in html at once, However perform the parse is a browser task and they do very fast.

In short, if you’re attaching, I’d use appendChild or (insertAdjacentHTML, see below).

If you are replacing, there are very valid situations, where to use innerHTML is a better option than creating the tree yourself through the DOM API.

Performance

The olifern created a test performing the comparison of appendchild vs innerHTML and undoubtedly the appendChield is the fastest!

The operation consists of adding 12 nodes to an existing Parent with 1000 Children in three ways:

1 - parentNode.innerHTML +=

2 - parentNode.innerHTML =

3 - parentNode.appendchild within the loop

jsperf - appendchild vs innerHTML

Graph:

inserir a descrição da imagem aqui

The method with the best performance is the last. The last method does not need to read the current DOM or analyze it.

Finally, it’s worth mentioning insertAdjacentHTML, which is a function you can use to insert nodes and elements into or next to an element using an HTML string. You can attach to an element with it: theElement.insertAdjacentHTML ("beforeEnd", "o HTML vai aqui"); The first argument is where to put the HTML, your choices are:

  • beforeBegin
  • afterBegin
  • beforeEnd
  • afterEnd

Example insertAdjacentHTML jsfiddle

insertAdjacentHTML compartmentability

References: innerHTML += ..." vs "appendchild(txtNode)

  • 2

    Please quote the sources when translating content from the OS. http://stackoverflow.com/questions/2305654/innerhtml-vs-appendchildtxtnode

  • 2

    @That, I was looking for this link, I had created this response based on the answer of T.J. Crowder but when I went to add the references I could not find this link anymore, I was in a laboratory in college that cleans the histories.

8

I usually generate always via string. I always mount identado so that I have, as soon as I hit the eye, the view of what that code represents.

Example:

var htmlTabela = "<table>                   " +
                 "    <tr>                  " +
                 "        <td> Titulo </td> " +
                 "    </tr>                 " +
                 "</table>                  " ;

Making it so much easier for other programmers to maintain and understand how to create through objects.

And in case, for some reason, I need to have an object I use jQuery to transform it, just do this:

var objetoJquery = $(htmlTabela);

That way I can have the object and use all the power of jQuery to modify it.

7

Good morning, well, imagine the situation that you have a table that has different themes according to the time, day the table is clear and night the table is darker, you will have different classes for this table, ie in your second code, you use extensive strings with style directly in html, now let’s assume that you do not use the style, but in the string itself put there "class=table_day", has improved your code, however, and when you change the class? will have to have another whole string for this change, for this reason example I prefer the creation of elements with pure JS in which I use setAttributes passing my classes that are variable that I can change easily , generates a good maintainability of your code...

remembering that this is just my point of view...

I hope it helped! Hugs;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.