Is there a difference in creating HTML elements in javascript?

Asked

Viewed 74 times

6

There is a difference in the creation of HTML elements in javascript ?

Example:

Like 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);

1 answer

4


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

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

Major 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’re aware of what you’re doing, and the value comes from a secure source, then theoretically there are no problems. But the fact that it is safe does not guarantee that its code does not have bugs, then it is possible that even in this case the use of innerHTML can lead to security problems.

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

Anyway, in several cases the difference in the creation of the elements is zero, but if you use the innerHTML you need to worry about more details than if you were to use the DOM’s creation functions. That reply from Soen shows some situations where to use the innerHTML may make sense, but personally I avoid its use for the reasons I mentioned above.

Browser other questions tagged

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