Categories
Asp, Asp.net

How to Create DIV Dynamically using JavaScript

How to Create DIV Dynamically using JavaScript

In this post we will learn How to Create DIV Dynamically using JavaScript. Here we are using javascript to accomplish this. We have used the appendChild method for document body element. AppendChild method takes one parameter as the name of the object of newChild that you want insert into the specified HTML tag like body tag in the above example. You can use the document.getElementById method of javascript passing the id value of any HTML tag along with appendChild method to insert the dynamic new HTML element into the specified id of the HTML tag.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css">
body {
width: 980px;
margin: 0px auto;
text-align: center;
padding-top: 50px;
font-size: 20px;
}
.dynamicDiv {
width : 200px;
height : 100px;
border : solid 1px #c0c0c0;
background-color : #e1e1e1;
padding : 5px;
}
</style>
<script type="text/javascript">
     function createDiv() {
     var divTag = document.createElement("div");
     divTag.id = "div1";
     divTag.setAttribute("align", "center");
     divTag.style.margin = "0px auto";
     divTag.className = "dynamicDiv";
     divTag.innerHTML = "This HTML Div tag is created dynamically using Javascript.";
     document.body.appendChild(divTag);
 }
</script>
<title>How to Create DIV Dynamically using JavaScript</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>How to Create DIV Dynamically using JavaScript</h1> 
<input id="btn1" type="button" value="Create Div" onclick="createDiv();" />
<br /><br />
<br /><br />
All rights reserved by <a href="http://www.hightechnology.in">www.Hightechnology.in</a> |
Hosting partner <a href="http://www.grootstech.com" target="_blank">Grootstech</a>     
</div>
</form>
</body>
</html>