Search code examples
javascripthtmlloopsiframeecmascript-2016

How to remove all `iframe` tags that are only in the current webpage?


I have a webpage that has various iframe tags.

I want to remove a certain iframe that has visible content on that webpage but I couldn't find a selector for it, so I thought deleting all iframes would help:

var iframes = document.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) {
  iframes[i].remove();
}

Yet, deleting all iframe tags brought another problem:

Each time I click on links aimed to open a modal (a popup), I get blank popups.

Seems that by deleting all iframe tags in my webpage, I've deleted them in other webpages appearing as modals or "sub-webpages", for my webpage.

How to remove all iframe tags that are only in the current webpage?

Update

I would have preferred an all vanilla way.


Solution

  • You can use expression that is used by jQuery to test if element is visible:

    function isVisible(elem) {
        return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
    }
    
    var iframes = document.querySelectorAll('iframe');
    for (var i = 0; i < iframes.length; i++) {
      if (isVisible(iframes[i])) {
        iframes[i].remove();
      }
    }