So, from what i understand you are just adding some text that is coming from the server to an array of children. And the children should be at the end of the parent element( after the existing children ) . You can use appendChild for that.
This way you control the HTML you are adding ( with document.createElement("div");
, and just insert plain text into it. The safety problem would be with HTML ( adding tags and etc ) but now, you know exactly what HTML you are adding. So this method ( imo ) is safe.
Because now even if you get a string of < script > do some hacking </script >
it will be added just as plain text when using the below method ( textContent just adds text, not HTML ) . So you won't have safety issues. But if you would insert < script > do some hacking < /script>
with a HTML method like insertAdjacentHTML()
then yes, that would be a problem :).
OFC its is better to add a parsing method that checks for script tags for example and other safety validations on the data you get from the server. ( This would be even better to do it on server side )
EDIT: if you want to add elements as siblings, use ( as you and torogadude correctly said ) insertBefore()
. or insertAfter()
depending on what you want to do.
So you just do it like this.
const mockArrayText = ['abc1','abc2','abc3'];
const existingElement = document.getElementById('add-here')
for (let i=0;i< mockArrayText.length; i++ ) {
const newElement = document.createElement("div");
newElement.textContent = mockArrayText[i]
existingElement.parentNode.insertBefore(newElement,existingElement.nextSibling)
}
<div id="add-here">
</div>