In this tutorial, you will learn how to create HTML elements using JavaScript.
Table of Contents
You can skip to a specific section of this JavaScript tutorial using the table of contents below:
- How to Create HTML Elements Using JavaScript
- How to Add a New HTML Element to a Page Using JavaScript
- The JavaScript
insertAdjacentElement
Method - Adding Longer Chunks of HTML to a Page Using JavaScript
- Final Thoughts
How to Create HTML Elements Using JavaScript
There are a few different methods that can be used to create new HTML elements using JavaScript.
The main way is using the document.createElement
method. This method takes a single argument - the type of HTML element that you are trying to create.
As an example, here is how we could use the createElement
method to generate an HTML <p>
tag and assign this new tag to a variable called paragraph
:
const paragraph = document.createElement('p');
Note that although we have created the new <p>
tag, we have not yet placed it anywhere on our page. This means that our page's appearance will remain unchanged.
This <p>
tag also contains no text and does not have any styling associated with it. Let's add some text and apply the red-font
class to this using the methods we learned earlier in this course.
First, let's change the value of the textContent
attribute of the paragraph
object:
paragraph.textContent = "This is the first HTML element that we created using JavaScript!";
Second, we can add the red-font
class by calling the add
method on the classList
attribute:
paragraph.classList.add('red-font');
Here's a summary of everything we've done so far:
const paragraph = document.createElement('p');
paragraph.textContent = "This is the first HTML element that we created using JavaScript!";
paragraph.classList.add('red-font');
Now that we have created and styled our HTML element, it's time to add it to our page.
How to Add a New HTML Element to a Page Using JavaScript
We can add our newly-created HTML element to our page by calling the appendChild
element on the document.body
object.
The document.body
object is an easy way to select the DOM while using JavaScript, and the appendChild
method allows us to add new elements to the DOM. We will pass the paragraph
variable into the appendChild
method to tell JavaScript to add our new HTML element to the page.
const paragraph = document.createElement('p');
paragraph.textContent = "This is the first HTML element that we created using JavaScript!";
paragraph.classList.add('red-font');
document.body.appendChild(paragraph);
You will notice that a new red paragraph with the text This is the first HTML element that we created using JavaScript!
appears at the bottom of the page. Nice!
It's important to understand the location of element injections when using the appendChild
method. To be more specific, the appendChild
method adds a new element to the end of an existing tag in JavaScript.
When you call it on document.body
, it naturally adds the element to the end of the page. You can also call the appendChild
on other types of HTML tags, such as <div>
tags or <span>
tags.
In the next section, we will learn about a different JavaScript method that provides more flexibility for HTML injection using JavaScript.
The JavaScript insertAdjacentElement
Method
Earlier in this course, we saw the insertAjacentText
method as a tool for adding text to an existing HTML element. JavaScript also includes a similar method called insertAdjacentElement
that provides similar functionality for HTML elements.
The insertAdjacentElement
method takes two arguments: position
and element
.
The position
argument specifies where the new element should be inserted relative to the parent object, and has four possible values:
- 'beforebegin': Before the targetElement itself.
- 'afterbegin': Just inside the targetElement, before its first child.
- 'beforeend': Just inside the targetElement, after its last child.
- 'afterend': After the targetElement itself.
The element
argument is the element you'd like to inject into your page.
Let's consider an example of how to use the insertAdjacentElement
method. Specifically, let's add a new <h1>
title to our page that says "This is Nick's example index.html file"
. This header can be placed at the very beginning of our index.html
file:
const header = document.createElement('h1');
header.textContent = "This is Nick's example index.html file";
document.body.insertAdjacentElement('afterbegin', header);
This technique is useful for adding an individual HTML element to a page, but can become cumbersome when adding multiple elements. You would have to use the createElement
and insertAdjacentElement
methods for each element you're adding, which would create a very long script.js
file.
Fortunately, there is a better way. In the next section of this tutorial, you will learn how to add longer chunks of HTML to a page using JavaScript.
Adding Longer Chunks of HTML to a Page Using JavaScript
Earlier in this course, we introduced the ``` character - often called the 'backtick' - as one way to create JavaScript strings. These backticks are also excellent candidates for injecting chunks of HTML into your webpage.
To do this, we first need to chose a container for the HTML that we are injecting into the website. We will specifically be using the <div>
element that holds the class of container
. We can select this HTML element with the following code:
const container = document.querySelector('.container');
Next, let's specify what HTML code we would like to inject into the page. Let's keep things simple and add a few paragraph tags:
<p>This is the first paragraph we're injecting into the page</p>
<p>This is the second paragraph we're injecting into the page</p>
<p>This is the third paragraph we're injecting into the page</p>
Now it's time to inject these <p>
tags into the <div>
element. To do this, we use the innerHTML
attribute of the container
object that we created using the querySelector
method.
Here's the code:
container.innerHTML = `
<p>This is the first paragraph we're injecting into the page</p>
<p>This is the second paragraph we're injecting into the page</p>
<p>This is the third paragraph we're injecting into the page</p>
`
There are a few important things you should understand about this code block:
- The paragraph tags between the backticks are just a normal JavaScript string. While the contents of the string happens to be HTML, it isn't HTML until it is actually dumped to the DOM when the page is rendered.
- This string used backticks - which is very important and discussed in more details below.
The use of backticks in this code is important for two reasons.
First, the backticks allow us to space the HTML code out over multiple lines. While the code would still function properly if it were all on the same line, spacing the HTML over multiple lines (the same way that it appears in the DOM) makes it much more readable.
Second, the use of backticks allows us to interpolate outside variables into the HTML, which crates many fascinating possibilities.
Here is a rudimentary example that has the same functionality as our previous code block but demonstrates the usefulness of string interpolation with HTML:
const element = "paragraph"
container.innerHTML = `
<p>This is the first ${element} we're injecting into the page</p>
<p>This is the second ${element} we're injecting into the page</p>
<p>This is the third ${element} we're injecting into the page</p>
`
Final Thoughts
In this tutorial, you learned how to create new HTML elements using JavaScript.
Here is a brief summary of what we covered:
- How to create new HTML elements using the
createElement
method - How to inject these new elements into your page using the
appendChild
method - How to use the
insertAdjacentElement
method to add elements to specific locations in the DOM - How backticks can be used to add longer chunks of HTML to a page with JavaScript