Using a String

Adding an HTML Element

Adding a simple HTML element to the page requires creating string, then add or insert then HTML element contained within the string to an existing HTML element using the innerHTML property or the insertAdjacentHTML() method.

A string literal can be used to represent a simple, static HTML element, which will be added to the existing HTML element, retrieved using either getElementById() or querySelector(). With the existing HTML element retrieved, the innerHTML property method can be used to add the new HTML element to the existing HTML element.

The innerHTML property can be used to get and set the HTML contained within an existing element. When getting HTML, the innerHTML property will return a string. When setting HTML, a string must be provided. JavaScript will automatically convert to the string into an HTML element.

NOTE

When adding HTML using innerHTML, any existing HTML inside of the target element will be overwritten.

const simpleHTML = '<h1>New Title</h1>'
const body = document.querySelector('body')

body.innerHTML = simpleHTML

Inserting an HTML Element

Using concatenation

When using the innerHTML property, the existing HTML will be overwritten. However, there will be times when we will want to insert HTML and keep the existing HTML. This can be accomplished by using innerHTML by using the concatenation operator (+).

const simpleHTML = '<h1>New Title</h1>'
const body = document.querySelector('body')

// insert the new element at the beginning
body.innerHTML = simpleHTML + body.innerHTML

// insert the new element at the end
body.innerHTML = body.innerHTML + simpleHTML

Using insertAdjacentHTML

Of course, this is limited to just inserting elements to be a first child or last child. In contrast, the insertAdjacentHTML() method inserts a HTML string into a specified position.

The method takes two arguments. The first is the position, which will consist of one of the four predefined positions (see below). The second is a string of HTML.

The four predefined positions are:

  • beforebegin: Before the element
  • afterbegin: Inside the element, before its first child
  • beforeend: Inside the element, after its last child
  • afterend: After the element
<!-- beforebegin -->
<div id="element">
  <!-- afterbegin -->
  <p class="child"></p>
  <p class="child"></p>
  <!-- beforeend -->
</div>
<!-- afterend -->

With the insertAdjacentHTML() method, it is possible to insert HTML anywhere on the page.

const simpleHTML = '<h1>New Title</h1>'
const body = document.querySelector('body')
const firstChild = body.querySelector(':first-child')

// insert the new element as after the first child
firstChild.insertAdjacentHTML('afterend', simpleHTML)