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
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 because
innerHTMLrenders complete markup rather than just text.
div.innerHTML = '<img src=x onerror="alert(\'XSS Attack\')">';
imgelement is injected into the div container.
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
Appending is not supported
Usually, we use
innerHTML, 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.
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!