Block all iframes from loading and replace with some text

I’m trying to block all iframes on a webpage from loading and replacing them with some text.

Any idea?

var iframes = document.getElementsByTagName('iframe');
for (var i = 0; i < iframes.length; i++) {
  var iframe = iframes[i];
  var div = document.createElement('div');
  div.innerHTML = 'Hello, I\'m an iframe';
  iframe.parentNode.replaceChild(div, iframe);

But it seems this only works for the first iframe. If i console log the number of iframes found it shows the actual number.

If i have 2 iframes it only works for the first, when i have 3 iframes it works for the first and the last.

>Solution :

getElementsByTagName is "live", it always reflects the current state of the DOM. So when you remove the first iframe, the second one moves to index position 0; but your for loop in the next iteration will access index 1 – and therefor skip an element.

You could loop over it backwards, then you would not have that problem; or use querySelectorAll instead in the first place – that one returns a static NodeList, so the changes you make to the DOM in your loop, won’t affect what the variable iframes contains.

Leave a Reply