Javascript Append Div Contents

by top54u.com 08 Jul, 2008

Javascript DOM provides number of methods to append Div tag contents dynamically. In Javascript code you can use innerHTML, innerText or appendChild methods to append the Div HTML tag’s contents. Same Javascript DOM methods can be used to append the content of other HTML elements also. You can concatenate the previous content and new content dynamically using document object along with its method getElementById.

 

Javascript getElementById method allows you to access the properties of specified HTML tag through its id attribute value passed to the getElementById method.

 

Syntax for Javascript Append Div Contents Methods

 

document. getElementById("id") .innerText = "value";

 

document. getElementById("id") .innerHTML = "value";

 

document. getElementById("id") .appendChild( newChild );

 

 

Above syntax codes for Javascript Append Div element content shows the innerText property that allows you to add plain text to the specified div element. innerHTML property allows you to insert HTML tags along with plain text into the specified Div to append its content. Last method of appendChild allows you to append Div with new HTML child elements along with dynamic text.

 

Example of Javascript Append Div Contents

 

 

<!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 Append Div Contents</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 <b>HTML Div tag</b> is created using Javascript DOM dynamically.";

 

document.body.appendChild(divTag);

 

 

var pTag = document.createElement("p");

 

pTag.setAttribute("align","center");

 

pTag.innerHTML = "This paragraph <b>HTML p tag</b> is added dynamically inside the div tag.";

 

document.getElementById("div1").appendChild(pTag);

}

 

</script> </head> <body>

 

<input id="btn1" type="button" value="create div" onclick="createDiv();" /> </body>

</html>

 

Above example will create a new HTML <div> tag along with innerHTML and nested HTML p tag having text. HTML <p> tag is inserted as child element using the appendChild method of Javascript.

Add comment


(Will show your Gravatar icon)  

  Country flag

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



Live preview

10/11/2008 3:38:53 AM