Best way of adding dynamic html?

What' the best way of adding html with dynamic information? Is it doing innerHtml = <div class="hourly__hour__key-info"> <h3>${dynamic info}/h3> <h3>${dynamic info}</h3> <h3>${dynamic info}</h3> </div> Is it creating a template for the html? is it creating new elements and adding all the classes and attributes?
11 Replies
Rägnar O'ock
Rägnar O'ock2y ago
If you do that the string literal will be populated with whatever value is dynamic info and then passed to innerHTML. innerHTML will take the given string and will update the DOM so it's as if you had this exact string in the original HTML file
Rägnar O'ock
Rägnar O'ock2y ago
Element: innerHTML property - Web APIs | MDN
The Element property innerHTML gets or sets the HTML or XML markup contained within the element.
Errtu
ErrtuOP2y ago
Is that the best/safest way to add the dynamic html? Or does it not matter?
Rägnar O'ock
Rägnar O'ock2y ago
If you are worried about injections (and you should if the dynamic info is not 100% originating from the js code) you should use textContent to add the value into the DOM. That way it will be automatically escaped by the browser
Rägnar O'ock
Rägnar O'ock2y ago
Element: innerHTML property - Web APIs | MDN
The Element property innerHTML gets or sets the HTML or XML markup contained within the element.
Errtu
ErrtuOP2y ago
If I reading this right, you shouldnt use it on information that could be security risk, like in a bank website, or medical. But something using an information API its fine?
Rägnar O'ock
Rägnar O'ock2y ago
Security here is used in the general sense, as in "if you don't want malintented people to do wakky things with your stuff you should do this..."
Jochem
Jochem2y ago
basically, don't use innerHTML unless you can personally vouch for every single bit of data in what you're setting as for setting inner(HTML|Text) vs building the elements one node at a time, it's a trade off. You can do lots at the same time with innerText, but if all you need is a button and that button has an onclick handler, you're probably better off building it manually with document.createElement
Errtu
ErrtuOP2y ago
Thank you both, does innerText and innerHTML have same issues with secruity?
Jochem
Jochem2y ago
sorry, I meant textContent like Ragnar said hm, actually, either textContent or innerText won't set the contents of an element in such a way that you can add more elements inside of it, that's just innerHTML so unless you can vouch for the content, you need to use the method mentioned in the link Ragnar posted,
Errtu
ErrtuOP2y ago
Thank you both. Still bit confused, but now i have good direction what to research. Both of you enjoy rest of your day.
Want results from more Discord servers?
Add your server