How to Create new DOM elements using JavaScript
Table of Contents
The great thing about JavaScript is that you can do a lot of things programmatically.
One of these things is being able to create new DOM elements.
This is how libraries like React and Vue work, they internally manage state and then manipulate the DOM by editing, creating and deleting elements from the DOM.
In this post, we'll learn how to create new DOM elements using JavaScript.
Creating a new DOM element
To create a new DOM element, we can use the document.createElement
method.
This method takes a string as an argument, which is the name of the element we want to create.
JAVASCRIPTconst element = document.createElement("div");
Once we have our element, we can do things like changing the text inside of it, the background color, or add a class to it:
JAVASCRIPTconst element = document.createElement("div");
element.innerText = "Hello world";
element.style.backgroundColor = "red";
element.classList.add("my-class");
Now we can just append it to the body so that we can see it on our screen:
JAVASCRIPTconst element = document.createElement("div");
element.innerText = "Hello world";
element.style.backgroundColor = "red";
element.classList.add("my-class");
document.body.appendChild(element);
- JavaScript
That creates a DOM markup that looks like this:
HTML<div class="my-class" style="background-color: red;">Hello world</div>
We can manipulate much more than just that, we can also add event listeners to our elements, and much more.
Feel free to look at the docs for more information.
Conclusion
In this post, we learned how to programmatically create a new DOM element, and then append it to the body.
Simply use document.createElement
and pass it the tag of the elment you want to create, then you can manipulate it however you want.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Express
- How to Serve Static Files with Nginx and Docker
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Using Puppeteer and Jest for End-to-End Testing
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React