Skip to content Skip to sidebar Skip to footer

Walk Up Dom Through Multiple Iframes In Vanilla Js

I'd like to be able to walk up the DOM from inside one or more nested iframes to grab and empty the parent div of the top iframe. I'd like my JS to work if there's just one iframe,

Solution 1:

If you don't find the correct div, you have to go up to the next iframe (or top level window) using parent

function getAdSlot(win) {
  var el = win.frameElement.parentNode;
  for (; el; el = el.parentNode) {
    if (el.classList && el.classList.contains('ad-unit')) return el;
  }
  // Reached the top, didn't find it 
  if (parent === top) {
     return false;
  }
  // Try again with the parent window 
  return getAdSlot(parent);
}
var el = getAdSlot();
console.log(el);
el.innerHTML = '';

Post a Comment for "Walk Up Dom Through Multiple Iframes In Vanilla Js"