What are the other options for inserting HTML generated from Javascript into the DOM besides .innerHTML?

Viewed 88

Common practice is to place dynamic generated HTML in a container element using .innerHTML. It makes logical sense for static positioned elements that fit in the page flow.

What if you are generating HTML elements that are being positioned with FIXED? Is it necessary to create a placeholder element and use placeholder.innerHTML to insert the generated element into the DOM? Using a placeholder seems a bit counter-intuitive since the new HTML won't actually be displayed in that position in the rendered document flow.

Also, Is there performance implications if you were generating a large number of fixed elements? Is there a faster way to tell the browser "Here's an element I want rendered in fixed position on top of everything else." ?

2 Answers

Fortunately, someone on Discord provided an answer. It appears I was asking the wrong question. I needed to use innerHTML, but I could do it on the body as an append instead of overwriting innerHTML in a placeholder container.

document.body.innerHTML += someHtml;

This will append the html to the end of the document, which eliminates the need for a container and implies intent.

There was no mention of performance or alternatives that don't modify the DOM, but I suspect this method is as good as it gets.

You can use the insertAdjacentHTML() method.

document.querySelector('div').insertAdjacentHTML('beforebegin', 'beforebegin')

document.querySelector('div').insertAdjacentHTML('afterbegin', 'afterbegin')

document.querySelector('div').insertAdjacentHTML('beforeend', 'beforeend')

document.querySelector('div').insertAdjacentHTML('afterend', 'afterend')
<div style='border: solid 1px red'>
  <br>
  Some text
  <br>
</div>

Alternatively, you could also use appendChild() with a text node like so:

var txt = document.createTextNode('Some more text')

document.querySelector('div').appendChild(txt)
<div>
  Some text
  <br>
</div>

Related