<!DOCTYPE html><html><head> <metacharset="utf-8"> <title>JS CreateElement Demo</title></head><body> <script> let div = document.createElement('div'); div.id = 'content'; div.innerHTML = '<p>CreateElement example</p>'; document.body.appendChild(div); </script></body></html>Code language: HTML, XML (xml)
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:
let div =document.createElement('div');div.id ='content';div.innerHTML ='<p>CreateElement example</p>';document.body.appendChild(div);Code language:JavaScript (javascript)
Adding a class to the div
The following example set the CSS class of a new div note:
let div =document.createElement('div');div.id ='content';div.className ='note';div.innerHTML ='<p>CreateElement example</p>';document.body.appendChild(div);Code language:JavaScript (javascript)
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:
// create a new div and set its attributeslet div =document.createElement('div');div.id ='content';div.className ='note';// create a new text node and add it to the divlet text =document.createTextNode('CreateElement example');div.appendChild(text);// add div to the documentdocument.body.appendChild(div);Code language:JavaScript (javascript)
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:
let div =document.createElement('div');div.id ='content';div.className ='note';// create a new heading and add it to the divlet h2 =document.createElement('h2');h2.textContent ='Add h2 element to the div';div.appendChild(h2);// add div to the documentdocument.body.appendChild(div);Code language:JavaScript (javascript)
2) Creating new list items (li) example
Let’s say you have a list of items:
<ulid="menu"> <li>Home</li></ul>Code language: HTML, XML (xml)
The following code adds two li elements to the ul:
let li =document.createElement('li');li.textContent ='Products';menu.appendChild(li);li =document.createElement('li');li.textContent ='About Us';// select the ul menu elementconstmenu=document.querySelector('#menu');menu.appendChild(li);Code language:JavaScript (javascript)
Output:
<ulid="menu"> <li>Home</li> <li>Products</li> <li>About Us</li></ul>Code language: HTML, XML (xml)
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:
let script =document.createElement('script');script.src ='/lib.js';document.body.appendChild(script);Code language:JavaScript (javascript)
You can first create a new helper function that loads a JavaScript file from an URL: