How to Create Element in Javascript
In this tutorial, you will learn how to create element in javascript. If you are a newbie, then you might face trouble in creating an element and then adding that element to the DOM. However, we do have certain methods to accomplish such things but everything should be done in the right sequence.
The createElement()
and createTextNode()
methods can take care of creating an element and creating a text code node for it. The appendChild()
method will be enough to add it to the DOM if you are expecting your newly created element to be a child of an existing element.
However, we are also going to cover the insertBefore()
method to add our newly created element just before an existing element. In the following example, we have a couple of elements. Upon click of a button, we will dynamically create an element and add it to the DOM. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,button
, andp
). Thediv
element is just a wrapper for theparagraph
element. - The inner text for the
button
element is“Create”
. - We have some random text in the
paragraph
element. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <button>Create</button> <div class="container"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Consectetur exercitationem labore saepe facilis placeat sunt quam laudantium illo dignissimos voluptates ipsa odio reprehenderit, atque maiores culpa necessitatibus, ipsam delectus? Aliquam.</p> </div> <script src="script.js"></script> </body> </html>
.container { border: 1px solid black; padding: 10px; margin-top: 10px; }
Javascript
- We have selected 2 elements
button
anddiv
using thedocument.querySelector()
method and stored them inbtnCreate
andparentElement
variables respectively. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are creating an
h1
element using thecreateElement()
method and storing it in theelement
variable. - We need some text content in the
h1
element and that is why we are using thecreateTextNode()
method. We are storing the text node in theelementContent
variable. - We are using the
appendChild()
method to add text content to our newly createdh1
element. - We can add our newly created element at 4 different locations.
- To add after
paragraph
element, we are using theappendChild()
method ofdiv
element and passing our new element as a parameter. - To add before
paragraph
element, we are using theinsertBefore()
method of div element and passing our new element and theparagraph
element as a parameter. - To add before
div
element, we are selectingbody
element and callinginsertBefore()
method. We are passing our new element and thediv
element as a parameter. - To add after
div
element, we are selectingbody
element and callinginsertBefore()
method. As a parameter, we are passing our new element and the next sibling of thediv
element. ThenextElementSibling
property returns the element immediately following the specified element, in the same tree level.
let btnCreate = document.querySelector('button'); let parentElement = document.querySelector('.container'); btnCreate.addEventListener('click', () =>{ let element = document.createElement('h1'); let elementContent = document.createTextNode('Hello World'); element.appendChild(elementContent); // parentElement.appendChild(element); // parentElement.insertBefore(element, document.querySelector('p')); // document.querySelector('body').insertBefore(element, parentElement); document.querySelector('body').insertBefore(element, parentElement.nextElementSibling); });