The power of DIV with IFRAME - Using a DIV as variable to write into IFRAME: discussion (Page 2 of 5 )
Looking at the code from the previous section, the first important issue to consider is the following:
<div id="dvSample"> <!-- <html> <body> Hai, this is from Div! </body> </html> --> </div>
That is simply a DIV containing some information (inside the comments) which is needed to send to IFRAME dynamically.
Let me explain the function “Show” part by part. Let us consider the following first:
var tDiv = document.getElementById("dvSample");
The above statement tries to find the DIV tag in our document (which is specified earlier). The handle of the DIV tag is stored in “tDiv.”
var FirstElement = tDiv.firstChild; var v = FirstElement.nodeValue;
The first statement tries to find the first element within the DIV (which is nothing but the comment). The second statement mainly retrieves the whole content available within the comment (which is nothing but the entire HTML available).
var tFrame = document.getElementById("myFrame");
The above statement tries to retrieve the handle of the IFRAME, which is declared in our web page with the ID “myFrame.” Proceeding further, we have the following:
var doc = tFrame.contentDocument; if (doc == undefined || doc == null) doc = tFrame.contentWindow.document;
To write some content to the IFRAME, we need to get the handle of the “document” object of the specific IFRAME. This is achieved through the above statements. The “if” statement is a simple “hack” to make it work with different browsers. Continuing, we have the following:
doc.open(); doc.write(v); doc.close();
Once we get the handle of the “document” object of the respective IFRAME, we need to open it, write the content and close it. The three above do the same. The content which needs to be written into the IFRAME is stored within the variable “v” (at the beginning).
Not only can we use simple information, but we can also embed any HTML into DIV when necessary. You can replace the above DIV with the following and test it once again:
<div id="dvSample"> <!-- <html> <body> <h1>heading</h1><hr> Hai, this is content! </body> </html> --> </div>