The innerHTML property of the Document Object Model (DOM) is used to set or return an element’s HTML content.
Since it is the easiest and quickest way to change the Document Object Model, the innerHTML property is frequently used to change the content of webpages.
How innerHTML can be dangerous?
The website can become very vulnerable if innerHTML is used constantly. For instance, using it for input fields can cause DOM manipulation, and attackers can use cross-site scripting (XSS) to insert harmful scripts and steal the private and sensitive data stored in session cookies.
As a result, we will learn about the drawbacks of using innerHTML in this article.
Disadvantages of using innerHTML property
-
Security Risk
As we discussed earlier in this article, innerHTML can lead to serious security vulnerability.
The idea behind an XSS attack with
innerHTMLis that malicious code is injected into your site and then executed. This is possible becauseinnerHTMLrenders complete markup rather than just text.For example,
div.innerHTML = '<img src=x onerror="alert(\'XSS Attack\')">';When the javascript file is loaded, the
imgelement is injected into the div container. -
Slow Process
innerHTMLis much slower to use because its contents are slowly built, and previously parsed contents and elements must be re-parsed, which takes time. -
Can break the document
innerHTMLdoes not provide proper validation, so any valid HTML code can be used. This may cause the JavaScript document to break. Even broken HTML can be used, which may cause unexpected problems. -
Appending is not supported
Usually, we use
+=to append in Javascript. When appending ininnerHTML, the whole HTML element is re-parsed.<p id="sentence">quick brown fox jumps over the lazy dog</p> sentence = document.getElementById('sentence') // The whole element have re-parsed sentence.innerHTML += '<p> Hello world </p>' -
Content is replaced everywhere
No matter what you add, change, or remove, the content passed in
innerHTMLwill replace everything you’ve written in HTML.HTML --- <h1 id="title">Hello World</h1> --- JS --- const title = document.getElementById('title') title.innerHTML = "quick brown fox jumps over the lazy dog" ---
What is the safe alternative to innerHTML?
One super and simple approach is to use textContent instead of innerHTML. This only injects the text content, no markups and no DOM manipulation.
div.textContent = 'quick brown fox jumps over the lazy dog'
If you are allowed using third-party library, then check out DOMPurify which will sanitize HTML and prevent XSS attacks.
Conclusion
Now, you know why you should not prefer using innerHTML property. I hope you have enjoyed reading the article.
Thanks for reading
Let’s connect on Twitter
Thanks for reading!