createElement() : Create an element node

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>
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


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer