Javascript Code to Change Div Object innerHTML

Updated on 23 Mar 2012,
Published on 26 Jun 2008

Javascript Code to change div object's innerHTML is very much similar to the code we did in the previous article Javascript code to change span innerText. Difference between innerText and innerHTML property of getElementById method of Javascript document object is that, innerText does not allow HTML tags inside the string value passed to the innerText property whereas innerHTML property allows to pass the HTML tags such as nested <p> tag, child <div> tag, <span> tag, text formatting tags link <b> bold tag, <strong> tag etc. You can also use inline styles and attribute values in the innerHTML string value passed. But you have to use Javascript string escape characters very precisely to pass the attribute values enclosed in quotation (" ") marks.

JavaScript DOM Examples:

You can see the live samples and examples of JavaScript DOM from the following links:

To provide all above functionality using Javascript DOM features you have to specify the value for id attribute of div element of HTML so that javascript document object could access the target div element using getElementById method, provided value of id attribute must be unique in the HTML document.

Javascript Syntax to change div innerHTML

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

innerHTML property of getElementById method of DOM document object of Javascript can get and set the innerHTML of specified HTML element whose id is passed to the getElementById method.

Javascript Code to change Div innerHTML

<html>
<head>
    <title>Javascript Change Div InnerHTML</title>
    <script language="javascript" type="text/javascript">
    <![CDATA[
        function changeDivHTML() {
            var previousInnerHTML = new String();

            previousInnerHTML = document.getElementById('div1').innerHTML;

            previousInnerHTML =
                              previousInnerHTML.concat("<h1>New HTML Text" 
                              + " added to the div HTML tag.</h1>");

            previousInnerHTML =
                              previousInnerHTML.concat("<p align=\"center\">" 
                              + "Paragraph child HTML element added<br /> to "
                              + "the div tag dynamically.</p>");

            previousInnerHTML =
                              previousInnerHTML.concat(
                              "<span style=\"color:#ff0000\">Span child HTML "
                              + "element added to the div tag dynamically." 
                              + "</span>");

            document.getElementById('div1').innerHTML = previousInnerHTML;
        }
    ]]>
    </script>
</head>
<body>
    <div id="div1">
        <b>innerHTML</b> placed inside the <b>div</b> element of HTML.<br />
        Javascript will change the innerHTML of this HTML div element.
    </div>
    <center>
        <input type="button" 
                value="Change Div innerHTML" 
                onclick="changeDivHTML()" />
    </center>
</body>
</html>

Note: Above example also shows how to code for attributes inside the string that is passed to the Javascript innerHTML property of HTML element. String Escape character backslash \ is used to concat the inline quotation marks to enclose the attribute values.

Similarly you can change the innerHTML of <span> and paragraph <p> element of HTML dynamically using Javascript DOM.

Output:

You can see the output of above discussed code from the following link:

Change Div InnerHTML

Continue to next tutorial: Javascript Get Height of Div onclick to learn how to retrieve the height of HTML Div element programatically.

9 Responses to "Javascript Code to Change Div Object innerHTML"
Chris
When I use the line:

previousInnerHTML = document.getElementById('div1').innerHTML;

I get an "object required" error in IE (works fine in Firefox). Any thoughts?
this code is very useful. thank you.
I adapted this to build a table of <div>'s which contained tables of single cells.

Functions, only two are active and appear in the script change the background colour of Tables 1 and 2. That all works fine in Opera, Chrome and Firefox but in IE8 (and my HTML editor IE influenced) the change is made but a paragraphing type operation occurs.

In the first function I've used "\" as advised but not in the second, both appear to work identically in the above browsers.

My code, and it is run within <body> tags:

<body>
<script language="javascript">
var tabst1="<table width='200px' border='1' bgcolor=";
var tabst2="<table border='1' ><td width='50px' align='middle' valign='center' bgcolor=";
var tabend="</td></tr></table>";
var skip="</tr><tr height='25px'>";
var divtabend="</td></tr></table></div></td>";
var ID="<td><div id='div";
var inbutton="<td width='50px' align='middle'><input type='button' value='";

document.write(tabst1+"'yellow'><tr height='25px'>");
for (a=1;a<17;a++){
document.write(ID+a+"'>"+ tabst2+"'blue'>"+a+divtabend);
if(a==4||a==8|a==12){
document.write(skip);
}
}
document.write(tabend);

document.write("<br><br>");

document.write(tabst1+"'yellow'><tr height='25px'>");
for (a=1;a<17;a++){
document.write(inbutton+a+"' onClick='press"+a+"()'></td>" );
if(a==4||a==8|a==12){
document.write(skip);
}
}
document.write(tabend);
var replaceDiv=new String();

function press1(){
a=1;
replaceDiv=document.getElementById('div1').innerHTML;
replaceDiv='';
replaceDiv=replaceDiv.concat("<table border=\'1\'><td width=\'50px\' align=\'middle\' valign=\'center\' bgcolor=\'red\'>"+a+divtabend);
document.getElementById('div1').innerHTML=replaceDiv;

}
function press2(){
a=2;
replaceDiv=document.getElementById('div2').innerHTML;
replaceDiv='';
replaceDiv=replaceDiv.concat(tabst2+"'red'>"+a+divtabend);
document.getElementById('div2').innerHTML=replaceDiv;
}
</script>
Hi,
I am using a function to add more text fields besides a textfield. These textfields are having the same name. I am not able to acess the innerHTML elements to validate. If the user leaves these innerHMTL textfields blank i shuld restrict/alert him about the error.can you please help me on this issue.
Ezineasp.net
Hi Kiran Kumar You must add other text fields with unique "id" for each. Further you can access each field using document.getElementById Javascript method. Good Luck
I had earlier modified the above code but had issues with IE adding a space after the modified <div>. By removing the <div> references and setting the 'id' to <td> tags I found that I could use a single cell table to modify the background colour of the <td> obtaining the same result in IE as I did with Firefox (haven't tried this modified code in Opera or Chrome but expect it will work. See the sample for a short time at the Website Url supplied.
You should choose whether add unique ID for your element or use few javascript getElementById to get to the right element
Stefano
Hi,
I was trying to do an "insert comment form" like this where I'm writing now, and your code helped me to concat one pubblished comment under another one (I'm working in locale with Dreamweaver).
The question I ask you is: when I have inserted in my webpage varoius comments, when I refresh the page these comments disappear (sure, cause innerhtml works on div tag and doesn't write in it).
I was searching for a function or metod in JS that writes one comment between html tags and store it out of but in the html document, as if I wrote it directly in the body.
I prefer not to use PHP, ASP or db (I don't know these languages! xD)
Sorry if you don't understand, but my english is not perfect :P

Please reply at my email
@Stefano, what you want to do isn't possible. When a page reloads from being refreshed, it loads the original web page, not whatever was modified by innerHTML statements. Think carefully about what you're asking. If you store something in the document, but then refresh and reload the original, you've lost all your changes. You can use AJAX in the document to manage the changes, but it has to talk to a server-side function. You can't do what you want to do without doing something on the server side, and that means using PHP or ASP (or another server-side scripting language). Why not do an ASP page but code it in JavaScript on the server side instead of VBScript. You're already using JavaScript on the client side.
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email