Is there a difference in creating HTML elements in javascript?

6

Is there a difference in creating HTML elements in javascript?

Example:

As String:

document.body.innerHTML += '<h1>foo</h1>';

And with createElement:

var elemento_pai = document.body;
var titulo = document.createElement('h1');
elemento_pai.appendChild(titulo);
var texto = document.createTextNode("bar");
titulo.appendChild(texto);
    
asked by anonymous 11.03.2016 / 18:00

1 answer

4

In most cases, if the value of innerHTML does not come from the user , and is well-formed, there is no difference - the result will be the same.

The biggest problem with using innerHTML is that it can be used as a vector of a cross-site scripting attack . If the value you are using is not "clean", you may end up running unwanted code. Some platforms explicitly forbid the use of the setter of innerHTML , such as Windows Store applications created using HTML / JS.

Larger problems occur when the value used for the property comes from an untrusted source (for example, user input, or even a database whose value has not been cleared). But if you are aware of what you are doing, and the value comes from a safe source, then theoretically there are no problems. But being secure does not guarantee that your code does not have bugs , then it is possible that even then innerHTML can lead to security problems.

Another minor problem is that document functions ( createElement , createTextNode , etc.) make the necessary escape of the values you are using. If you want to create an element with a text node with abc<def>ghi&jkl , and you use innerHTML , you will have to worry about escaping the required characters ( < , > , & ), which is not the case using the functions of the document. One more potential source of bugs.

Anyway, in a number of cases the difference in element building is zero, but if you use innerHTML you need to worry about more detail than if you were going to use the DOM nodes functions. This SOen response shows some situations where using innerHTML might make sense, but personally I avoid using it for the reasons which I mentioned above.

    
11.03.2016 / 18:15