Is It a Security Risk to Use innerHTML Even If You Set the Value Yourself?
If the content you are injecting into innerHTML
is static and does not come from user input or any untrusted source, the security risk is significantly lower.
Apart from security issues, there are other drawbacks to using innerHTML as well.
If you are setting the values yourself, use safer alternatives like document.createElement
and Element.appendChild
which gives you more control over the DOM tree, enables reusability, and simplifies the addition of event listeners.
Using innerHTML
is like taking a shortcut and a sign of not-so-good coding practice, so it's recommended to use safer alternatives unless there are compelling reasons not to.
Get my free, weekly JavaScript tutorials
Want to improve your JavaScript fluency?
Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.
Join today, and level up your JavaScript every Sunday!
Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.