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
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
You can get more info about it here
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
Element: innerHTML property - Web APIs | MDN
The Element property
innerHTML gets or sets the HTML or XML markup contained
within the element.
Is that the best/safest way to add the dynamic html? Or does it not matter?
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
It's addresed here : https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations
Element: innerHTML property - Web APIs | MDN
The Element property
innerHTML gets or sets the HTML or XML markup contained
within the element.
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?
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..."
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
Thank you both, does innerText and innerHTML have same issues with secruity?
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,
Thank you both. Still bit confused, but now i have good direction what to research. Both of you enjoy rest of your day.