Create element

document.createElement("p")

const el = document.createElement("span")
el.innerHTML = "Hello <b>World</b>!"

Or create a document fragment which is empty, using createDocumentFragment.

const el = document.createDocumentFragment()
const innerEl = document.createElement("p")
innerEl.innerText = "Hello, World!"
el.appendChild(innerEl)

I canโ€™t get this to work with innerHTMl though.

const el = document.createDocumentFragment()
el.innerHTML = "<p>Hello <b>World</b>!</p>"

Insert

el.append(...)
el.appendChild(...)

Based on source.

To insert before an element.

function insertBefore(currentEl, newEl) {
    currentEl.parentNode.insertBefore(newEl, currentEl);
}

To insert after an element.

function insertAfter(currentEl, newEl) {
    currentEl.parentNode.insertBefore(newEl, currentEl.nextSibling);
}

Inner text

el.innerText = "Hello, World!"

Inner HTML

Note case.

el.innerHTML = "<p>Hello, <b>World</b>!</p>"

Using JS template literals:

const link = "https://example.com"
const el = document.createElement('p')
el.innerHTML = `See more info <a href="${link}">here</a>`

Codeblock

Example of creating a code snippet of options and adding it to the page as stringified JSON data.

const pre = document.createElement('pre')
const code = document.createElement('code')
code.innerText = JSON.stringify(options, null, 4)
pre.append(code)
insertAfter(el, pre)