Javascript Create New Div HTML Element Dynamically

by top54u.com 03 Jul, 2008
Spotlight.....

Javascript DOM features provide the functionality to create new HTML elements such as div, span, paragraph p tag etc. dynamically. document.createElement method of Javascript DOM provides the feature to create new div HTML element or other HTML elements dynamically. You can pass the name of the HTML tag that you want to create to the createElement method of document object. The object created by createElement method can access all the supported properties, functions and methods of document.documentElement method of Javascript. You can access the methods such as setAttribute, style, id and title etc.

 

Syntax for Javascript createElement method

 

document. createElement("HTML element name");

 

Above syntax of Javascript document. createElement method shows that you can pass the name of HTML Tag you want to insert into the HTML document.

 

E.g: document.createElement("div")

 

Above example code will create an instance for new div HTML element in Javascript.

 

Example of Javascript Create New Div HTML Element Dynamically

 

<!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>

<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 tutorial we will learn How to append the div content dynamically using appendChild method of Javascript.

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

8/23/2008 8:57:07 PM

OUR SPONSORS[+ advertise here]
related videos.....
recent posts.....
top54u ezines.....