Friday, August 8, 2008

How To Create Dynamic Div Using Javascript

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Javascript create new div</title>
    <style type="text/css">
   .dynamicDiv {
   width : 200px;
   height : 100px;
   border : solid 1px #c0c0c0;
   background - color : #e1e1e1;
   font - size : 11px;
   font - family : verdana;
   color : #000;
   padding : 5px;
   }
   </style>

    <script type="text/javascript" language="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 using Javascript DOM dynamically.";
   document.body.appendChild(divTag);
   }
    </script>

</head>
<body>
    <input id="btn1" type="button" value="create div" onclick="createDiv();" />
</body>
</html>
In the above example Javascript code to create new div HTML tag 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. In the next

No comments:

Post a Comment