Let's say my code was something pretty simple like this:
let content = "";
for(let i=0; i<array.length; i++){
content+='<h1>array[i]</h1>';
}
document.getElementById('some_id').innerHTML = content;
I don't like the idea of putting HTML in my JavaScript code, but I don't know any other way of inserting elements into the DOM without using innerHTML, JQuery's html() method, or simply creating new DOM elements programmatically.
In the industry or for best practices, what's the best way to insert HTML elements from JavaScript?
Thanks in advance!
document.createElementandnodeYouWishToExtend.appendChild(nodeYouCreated). For another way to do it all together, you can look at frameworks like React, Angular, Vue, Knockout, etc.arraycomes from, but assuming its something users can change, they could sneak in some "unsafe" values. For example<script type="text/javascript">doBadThing()</script>. Unless you're escaping your inputs, or using a library that does, you should never set innerHTML directly with user-originating inputs.content+='<h1>array[i]</h1>';will not evaluatearray[i]but instead print it as text.