createElement()

To create an HTML element, you use the document.createElement() method:

let element = document.createElement(htmlTag);Code language: JavaScript (javascript)

The document.createElement() accepts an HTML tag name and returns a new Node with the Element type.

1) Creating a new div example

Suppose that you have the following HTML document:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JS CreateElement Demo</title>
</head>
<body>

</body>
</html>Code language: HTML, XML (xml)

The following example uses the document.createElement() to create a new <div> element:

let div = document.createElement('div');Code language: JavaScript (javascript)

And add an HTML snippet to the div:

div.innerHTML = '<p>CreateElement example</p>';Code language: HTML, XML (xml)

To attach the div to the document, you use the appendChild() method:

Put it all together:

Adding an id to the div

If you want to add an id to a div, you set the id attribute of the element to a value, like this:

Adding a class to the div

The following example set the CSS class of a new div note:

Adding text to a div

To add a piece of text to a <div>, you can use the innerHTML property as the above example, or create a new Text node and append it to the div:

Adding an element to a div

To add an element to a div, you create an element and append it to the div using the appendChild() method:

2) Creating new list items (li) example

Let’s say you have a list of items:

The following code adds two li elements to the ul:

Output:

3) Creating a script element example

Sometimes, you may want to load a JavaScript file dynamically. To do this, you can use the document.createElement() to create the script element and add it to the document.

The following example illustrates how to create a new script element and loads the /lib.js file to the document:

You can first create a new helper function that loads a JavaScript file from an URL:

And then use the helper function to load the /lib.js file:

To load a JavaScript file asynchronously, you set the async attribute of the script element to true:

Summary

  • The document.createElement() creates a new HTML element.

  • The element.appendChild() appends an HTML element to an existing element.

Last updated