Let’s dive into one of the fundamental operations of web development: adding a new element to the Document Object Model (DOM) with JavaScript.
The DOM is the hierarchical structure that represents the HTML markup of a web page, and knowing how to manipulate it is the bread and butter for creating dynamic and responsive web applications.
Adding a new element to the DOM is a thing that needs to be done when building web pages, and mastering this requirement with JavaScript can be a powerful tool in your web development toolkit. So let’s get started!
Creating a New DOM Element
There’s more than one way to add a new element to the DOM, and each has its unique pros and cons. In this tutorial, however, we’ll focus on the two most common ways: using createElement()
and innerHTML()
.
Using the createElement() and appendChild() Methods
The createElement
method allows you to create a new HTML element using JavaScript. Here’s an example that creates a new div
element with the class name my-div
:
// Create element
const newDiv = document.createElement('div');
// Add my-div to class list (optional)
newDiv.classList.add('my-div');
In this example, we first create a new div
element using the createElement
method. We then add the class name my-div
to the element using the classList
property. Note that we didn’t append the new element to the DOM yet – we’ll do that in the next step.
Once you’ve created a new element using createElement
, you can add it to the DOM using the appendChild
method. Here’s an example that appends the newDiv
element we created in the previous step to the <body>
element:
// Append newDiv as a child element at the end of the <body> tag
document.body.appendChild(newDiv);
This method will add the newDiv
element to the end of the <body>
tag, nesting it inside that tag as a child element.
Of course, you can target any DOM element you want using a CSS selector with the querySelector()
method. Here’s an example that appeds newDiv
as a child of the element with an ID of #add-here
:
// Append newDiv as a child element at the end of the #add-here element
document.querySelector('#add-here')appendChild(newDiv);
Using the innerHTML() Property
Another way to add new elements to the DOM is to use the innerHTML
property. Here’s an example that creates a new div
element with the class name my-div
and adds it to the body
element of the web page using innerHTML
:
// Replace body contents with innerHTML
document.body.innerHTML += '<div class="my-div"></div>';
In this example, we use the innerHTML
property to add a new div
element with the class name my-div
to the body
element of the web page. This is a shorthand way of creating and adding a new element to the DOM, but it can be less efficient than using createElement
and appendChild
for more complex HTML structures.
How to Choose
As a general rule, if you’re adding simple, single elements like a div
or a p
tag, using innerHTML
can be a quick and easy way to get the job done.
However, if you’re adding more complex elements with many child elements or specific attributes, createElement
is usually the better choice. This allows you to build up the element’s structure programmatically and modify its attributes directly, which can be more efficient and easier to read and maintain than using a long string of HTML.
Also, and this is very important for web developers to understand, using innerHTML
to add new content to an element will replace any existing content that was previously inside that element. For example, if you have an HTML element with the id my-element
that contains some text:
<div id="my-element">Hello, world!</div>
And you use innerHTML
to add new content to it:
document.getElementById('my-element').innerHTML = '<p>This is new content!</p>';
The original content “Hello world!” will be replaced with the new content “This is new content!”. If you want to add content to the element without removing the existing content, you can use methods like appendChild
to add new child nodes to the element.
When using innerHTML
, be careful and sanitize any user input to prevent cross-site scripting (XSS) attacks. If the content being added to the DOM comes from user input, it’s important to sanitize it first to remove any potentially dangerous content. createElement
doesn’t have this concern, since it builds up the element programmatically instead of relying on user-generated content.
In Summary
Method | Advantages | Disadvantages | When to use |
---|---|---|---|
innerHTML | – Quick and easy to use – Allows you to add HTML as a string – Can be used to remove all child nodes at once | – Overrides existing content – Can introduce XSS vulnerabilities – Can be slower for large or complex HTML | – For simple, one-off additions to an element |
createElement | – More secure, as it does not rely on user-generated content – Allows you to add elements with specific attributes and child nodes | – More verbose and requires more code – Requires you to build up the element programmatically | – For adding more complex elements or structures programmatically – When you want more control over the added elements |