JavaScript document.createElement() Method
You are Here:
JavaScript document.createElement() Method
The document.createElement()
method creates the HTML element specified by tagName.
Note: If tagName isn't recognized, an HTMLUnknownElement will be created.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click Me</button>
<ul></ul>
<script>
var x = document.getElementsByTagName('ul')[0];
function myFunction() {
var list = document.createElement("li");
x.appendChild(list);
}
</script>
</body>
</html>
Syntax
document.createElement(tagName)
Parameter Values
Value | Type | Explanation |
---|---|---|
tagName | Required | A string that specifies the type of element to be created. |
Return Values
Value | Explanation |
---|---|
Object | Returns the new Element. |
createElement() with Data
To add data to the element created, use createTextNode() method.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click Me</button>
<ul></ul>
<script>
var x = document.getElementsByTagName("ul")[0];
function myFunction() {
var list = document.createElement("li");
var item = document.createTextNode("Apple");
list.appendChild(item);
x.appendChild(list);
}
</script>
</body>
</html>
createElement() to Display Data in an Array
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<ul></ul>
<script>
var x = document.getElementsByTagName("ul")[0];
var fruits = ["Apple", "Banana", "Cherry"];
var fragment = document.createDocumentFragment();
fruits.forEach(function(fruit) {
var li = document.createElement("li");
li.textContent = fruit;
fragment.appendChild(li);
});
x.appendChild(fragment);
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in JavaScript.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.