How to Replace the InnerHTML of a DIV With the InnerHTML of Another DIV
Successful Web developers understand the importance of being able to move the contents of one page object into another. DIV elements, for example, serve as container objects for headings, menus and other elements. Some DIVs may contain objects, while others may not. You can make the objects in one DIV appear in another DIV by replacing the innerHTML of the target DIV with that of the source.
Instructions
-
-
1
Launch your HTML editor or any text editor. Use it to open an HTML document.
-
2
Add the following code to that document's body section:
<div id="div1">
<h1>This Is a Heading Inside DIV 1</h1>
</div>
<div id="div2">
<h1>This Is a Heading Inside DIV 2</h1>
</div>
<input type="button" value="ReplaceHTML" onclick="replaceHTML('div1','div2')" />
This creates two DIV elements. Each DIV contains a unique heading. The button below the DIVs calls the "replaceHTML" function and passes the ID values of those DIVs to the function.
-
-
3
Add the "replaceHTML" function to the document's script section as shown below:
function replaceHTML(id1, id2) {
var obj1 = document.getElementById(id1);
var obj2 = document.getElementById(id2);
obj1.innerHTML = obj2.innerHTML;
}
This function obtains references to the two DIVs and sets the innerHTML of the first DIV with that of the second.
-
4
Save your document and view it in a browser. The two DIVs appear on the Web page.
-
5
Click the button. The code runs and replaces the contents of the first DIV with that of the second. The first DIV's heading changes to "This Is a Heading Inside DIV."
-
1
Tips & Warnings
Note the order in which the button click event passes the ID values of the two DIV elements. The JavaScript function replaces the contents of the first DIV in the argument list with the second DIV's contents. To replace the second DIV's contents instead, reverse the order of those elements in the argument list as shown: <input type="button" value="ReplaceHTML" onclick="replaceHTML('div2','div1')" />