Wednesday, July 21, 2010

A cross-browser solution to get iframe body element

An often task while web development is the working with iframe. If we have iframe's body object bodyIframe we can use quite normally JavaScript means to do for instance its content empty
...
bodyIframe.innerHTML = "";
...
or to get any HTML form like
...
var form = bodyIframe.getElementsByTagName("form")[0];
...
or something else. Unfortunately there isn't an uniform access to iframe's body object. It's dependent on browser. I have found out an universal way to get this element by iframe Id (<iframe id="..." .../>). The appropriate JS function looks as follows
function getIframeBody(iframeId)
{
   var obj = document.getElementById(iframeId);
   if (obj == null) {
      return null;
   }

   var bodyIframe = null;
   if (obj.contentWindow && obj.contentWindow.document.body) {
      bodyIframe = obj.contentWindow.document.body;
   } else if (obj.document && obj.document.body) {
      bodyIframe = obj.document.body;
   } else if (obj.contentDocument && obj.contentDocument.body) {
      bodyIframe = obj.contentDocument.body;
   }

   return bodyIframe;
}

1 comment:

Note: Only a member of this blog may post a comment.