Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading