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.
const evilInput = `<img src onerror="alert('evil')">`;
document.body.insertAdjacentHTML('beforeend', evilInput);
In terms of security, insertAdjacentHTML
is not really better than innerHTML
- what insertAdjacentHTML
is useful for is when
innerHTML
. OrinsertBefore
)Also, how should I go about completely refilling a table?
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
and insertAdjacentHTML
are both fine - use whatever makes the logic easiest)