Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it suggested to avoid .innerHTML?

Tags:

javascript

Sorry for being a JavaScript noob, but can anyone please explain why is it recommended not to use .innerHTML. When we have something that is faster and easier in form of .innerHTML , why shouldn't we use it ?

like image 512
heretolearn Avatar asked Aug 29 '13 04:08

heretolearn


People also ask

Why should you avoid innerHTML?

The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.

What is the disadvantage of innerHTML?

Disadvantages of innerHTMLIt is very slow because as inner HTML already parses the content even we have to parse the content again so that's why it takes time. When we have used the event handlers then the event handlers are not automatically attached to the new elements created by innerHTML.

Is innerHTML unsafe?

innerHTML is very useful and safe when rendering static content (and dynamic content you are completely in control of) to the DOM. However, the security risks associated with . innerHTML occur when this is used when working with user input.

What is the effect of using innerHTML?

Reading the HTML contents of an element Reading innerHTML causes the user agent to serialize the HTML or XML fragment comprised of the element's descendants. The resulting string is returned. This lets you look at the HTML markup of the element's content nodes.


1 Answers

innerHTML is a sledgehammer. It will blast away the contents of the selected DOM element and replace them with whatever happens to be assigned at the time. This leads to a number of HTML escaping and validation issues.

More importantly, for pages where a large number of events are bound, using innerHTML to append another element will regenerate DOM elements, which means event bindings can get lost.

There are also some issues regarding memory leaks in older versions of IE when elements are removed from the DOM.


With all of that said, I'm not telling you that you shouldn't be using innerHTML. I use it all the time in jQuery when I use $(selector).html(). Sometimes a sledgehammer is the right tool for the job, and when events are delegated properly it won't matter how much the content is reloaded.

like image 143
zzzzBov Avatar answered Oct 06 '22 23:10

zzzzBov