Wednesday, December 10, 2008

Creating HTML Elements through Javascript

This post describes how to create a simple html control or tag using javascript and add to the html page at the runtime.

For that we write a javascript function called CreateButton() which will be called on onload event of body tag.

Initially the html looks simple with only one div tag named 'mydiv' inside body .We are going to add button into this div.

<html>

<head>

<title>Dynamic control creation</title>

</head>

<body onload="createButton()" >

<div id="mydiv">

</div>

</body>

</html>

To create object of button use the following line of code

var btnNew = document.createElement("button");

We can set content by it's innerText property. Now add in to the div using appendChild method.The full script will look like as follows.

<script type="text/javascript">

function createButton() {

var btnNew = document.createElement("button");

btnNew.innerText = "Dynamic Button";

var mydiv = document.getElementById("mydiv");

mydiv.appendChild(btnNew);

}

</script>

We can associate event handlers to this child elements.The below code associates the same event handler(to create new button) to the newly created button.Hence a click on the new button creates one more new button and it continues...

<script type="text/javascript">

function createButton() {

var btnNew = document.createElement("button");

btnNew.innerText = "Create another button";

btnNew.setAttribute("onclick", createButton);

var mydiv = document.getElementById("mydiv");

mydiv.appendChild(btnNew);

}

</script>



No comments: