In this tutorial you will learn how to create div element dynamically by using javascript. We will do this by utilizing the DOM features of javascript. Let's have a look over example given below
Create div element dynamically by using javascript
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Create div element dynamically using javascript</title><style type="text/css">.myDivClass{color: #999;padding: 10px;width: 250px;height: 150px;border: solid 1px #666;}</style><script type="text/javascript" language="javascript">function CreateDivElement() {var divElement = document.createElement("div");divElement.id = "myDiv";divElement.className = "myDivClass";divElement.innerHTML = "Hello World!";document.body.appendChild(divElement);}</script></head><body><div><input id="myBtn" type="button" value="Click Me" onclick="CreateDivElement();" /></div></body></html>
And if you want to want to create div element inside any other html element of page body then nothing to worry. Let's suppose we have a div in our page which id is testDivlike given below
<div id="testDiv">
</div>
and you want to create div inside this testDiv. Just you have to change the last line of CreateDivElement() function from
document.body.appendChild(divElement);
to
document.getElementById('testDiv').appendChild(divElement);
and that's it. I hope you will like this tutorial.
0 comments:
Post a Comment