Removing an iframe from the DOM

I have the following button click function which is adding an iframe to the DOM. Here is the function showing how addframe is called. All other code inside the below function is irrelevant and I just wanted to show the call to addIframe function

buttonclick: function (row) {
              editrow = row;
             
              var dataRecord = $("#tierGrid").jqxGrid(
                "getrowdata",
                editrow
              );


              var boxId = dataRecord.id;


              var config = getUpdatedConfig();
              var opts = getUpdatedOptions(true);
              addIframe("${ctx}/labelpdf.htm?id=" + boxId);
              var iframe = document.getElementById("PDFframe");


              console.log("Display iframe variable below:");
              console.log(iframe);


              var pdfData = "";
              iframe.onload = function () {
                var content = iframe.contentDocument;


                if (content) {
                  pdfData = content.body.innerText;

                  var printData = [
                    {
                      type: "pixel",
                      format: "pdf",
                      flavor: "base64",
                      data: content.body.innerText,
                      options: opts,
                    },
                  ];


                  qz.print(config, printData).catch(displayError);
                }
              };
            }, // end of buttonclick: function (row) {

Here is my function:

function addIframe(url) {
    var x = document.createElement("iframe");
    x.setAttribute("id", "PDFframe");
    x.setAttribute("src", url);
    console.log("URL INSIDE addfFrame function");
    console.log(url);


    x.setAttribute("style", "visibility:hidden;");


    document.body.appendChild(x);
  }

Evetytime a button is clicked, an iframe is added in the DOM with same id PDFframe which looks wrong as we should not have
elements in the DOM with same ID. But I want to get rid of an old iframe as soon as button is clicked second time or third time etc
How should I go about it?
Is there a way I can completely remove the old iframe or do I need to add new ID dymanicammy everytime and keep on adding iframe to the DOM?

Yep. And you’ve already named the function.
Elements have a defined method:
.remove()
Which will remove them from the DOM. (Javascript so inventive with their naming.)

Before you create your new Iframe, getElementById the ID “PDFframe”.
If the thing you get back is not null (ie: it found and returned an element),
Call the remove method of that element.
Then continue your code as normal to create the new iframe element.

See if you can translate the above 4 lines into code :wink:

Bonus point: You dont need to create a new element every time. You can just retarget your existing iframe.

1 Like