I have recently found out that using setInnerHtml is not good practice as there are plenty performance and security issues associated with it. So I am wondering whether replacing setInnerHtml with "insertAdjacentHTML" is fine?
Also, how should I go about completely refilling a table? As in removing the children of the parent element, the table body, and repopulating it with insertAdjacentHTML.
What I am currently doing
document.getElementById('myid').innerHTML = "";
const elm = document.getElementById("myid");
elm.insertAdjacentHTML('beforeend', '<div></div>');
Does this practice defeat the purpose of using insertAdjacentHTML since I am still using innerHTML. When I set it empty with innerHTML, I am not doing any complex DOM manipulation, am I?
If the HTML to be inserted is not trustworthy,
insertAdjacentHTML
could allow for arbitrary code execution.In terms of security,
insertAdjacentHTML
is not really better thaninnerHTML
- whatinsertAdjacentHTML
is useful for is wheninnerHTML
. OrinsertBefore
)Setting the text content or
innerHTML
to the empty string and then choosing any of the safe approaches to insert elements anew is fine. (What qualifies as a safe approach depends on what exactly you're inserting. If it's from your trustworthy backend, for example,innerHTML
andinsertAdjacentHTML
are both fine - use whatever makes the logic easiest)