Using Strings
With the introduction of Template Literals, creating HTML has become much easier for novice developers, because Template Literals allow the developer to create HTML in JavaScript that looks and feels like writing in an HTML file.
Creating a Template
Using template literals, it is possible to create an HTML template, complete with white space, tabs, and carriage returns.
For example, if we wanted to create an HTML unordered list of animals with a title, we do so with a template literal.
const list = `
<h2>Animals</h2>
<ul>
<li>cat</li>
<li>dog</li>
<li>mouse</li>
</ul>`
Creating a Template with Placeholders
We can take this a step further by using placeholders in place of the text. Then using variables to recreate the HTML.
const title = 'Animals'
const animals = ['cat', 'dog', 'mouse']
const list = `
<h2>${title}</h2>
<ul>
<li>${animals[0]}</li>
<li>${animals[1]}</li>
<li>${animals[2]}</li>
</ul>`
innerHTML
Inserting Templates with There are two common techniques to insert a template into the HTML. The first is to use the innerHTML
property and the second is to use the insertAdjacentHTML()
method.
Note
Both these techniques require a string and therefore will NOT work with the createElement()
method discussed in the next section.
The innerHTML
property of any HTML element will contain all of the HTML that within the element.
Like any other property, it is possible to change an element's innerHTML
by using an equals sign =
and followed by the string HTML.
Note
Changing an element's innerHTML
will remove any existing HTML inside the element. To keep the existing HTML, you must include the element's innerHTML
after the equals sign.
innerHTML
Using a Loop with While the above example works to create and insert new HTML, it would not be easy to maintain if additional animals are added to the list. This is where loops come in.
By using a loop to iterate over the array, it is possible to create the list item HTML without the need for additional HTML for each new animal.
In the example below, we are using the for...of
loop to iterate over the array, and storing each list item to a new array, items
. This new items
array is then inserted into our template literal using the join()
method to convert array to a string.
insertAdjacentHTML()
Inserting Templates with Unlike the innerHTML
property, which replaces the all the HTML of an element, the insertAdjacentHTML()
method inserts HTML string into an element at a specified position.
The method takes two parameters. 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 elementafterbegin
: Inside the element, before its first childbeforeend
: Inside the element, after its last childafterend
: After the element
<!-- beforebegin -->
<div id="element">
<!-- afterbegin -->
<p class="child"></p>
<p class="child"></p>
<!-- beforeend -->
</div>
<!-- afterend -->