Search code examples
iframeappendchild

How to replace an existing iframe instead of appending it to the document body?


While rendering iframes, I use the code:

ifrm = document.createElement("IFRAME");
ifrm.style.width = "100%";
ifrm.style.height = 600+"px";
function makeFrame() {
document.body.appendChild(ifrm);
}

However, this keeps appending iframes below the existing one, each time I call the function makeFrame(). So, if I call makeFrame() (say thrice), then I get three iframes one below the previous. How to prevent this and replace the existing one instead of appending to the last one?


Solution

  • The simplest answer:

    If you want to change your code as little as possible, and you're certain that you'll only have exactly one iframe on the page at any given time

    function makeFrame() {
    oldiframe = document.getElementsByTagName("IFRAME")[0] 
    // getElementsByTagName will return an array (a list). 
    // Adding [0] will return the first (and, under our assumptions, only) element
    ifrm = document.createElement("IFRAME");
    ifrm.style.width = "100%";
    ifrm.style.height = 600+"px";
    document.body.replaceChild(ifrm, oldiframe);
    }