<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:
Post a Comment