dhairyashah
Portfolio

Dec 3rd, 2022

Why InnerHTML Is a Bad Idea and How to Avoid It?

Author Picture

Dhairya Shah

Software Engineer

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

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!