createElement() : Create an element node
JavaScript
document
DEMO : Create element dynamically →
<html>
<head>
<title></title>
</head>
<body>
<input type=button onClick='add_element()'; id=b1 value='Add Element'>
<br><br>
<script type="text/javascript">
function add_element(){
b2 = document.createElement("button");
b2.innerHTML = " New Button ";
document.body.appendChild(b2);
}
</script>
</body>
</html>
Note that while createElement() allows us to create new elements, it won't display them until we add them to the DOM (Document Object Model) using methods like appendChild()
In above code we used body as parent element. We can use existing element also. Here we are adding one <p> element with different background colour than the parent <div> element.
DEMO : Add to parent element dynamically →
<html>
<head>
<title></title>
<style>
div {
background-color: lightblue;
}
p {
background-color: yellow;
}
</style>
</head>
<body>
<input type=button onClick='add_element()'; id=b1 value='Click to Add Element'>
<br><br>
<script type="text/javascript">
function add_element(){
msg = document.createElement("p");
msg.innerHTML = " JavaScript section ";
document.getElementById("my_div").appendChild(msg);
}
</script>
<BR>
<div id=my_div>Welcome to plus2net</div>
</body>
</html>
Syntax
document.createElement(type_of_element)
Adding List item
DEMO : Add to item to a List →
<html>
<head>
<title>Demo </title>
</head>
<body>
<input type=button onClick='add_element()'; id=b1 value='Click to Add Dinner'><br><br>
<script type="text/javascript">
function add_element(){
my_new = document.createElement("li");
text = document.createTextNode("Dinner");
// Append text node to "li" element:
my_new.appendChild(text);
my_list=document.getElementById("my_list");
my_list.insertBefore(my_new, my_list.children[2]);
}
</script>
<BR>
<OL id=my_list>
<li>Breakfast</li>
<li>Lunch</li>
</OL>
</body>
</html>
← document Object getElementsById → Last Modified date of the page →
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
plus2net.com