Last active
August 29, 2015 13:56
-
-
Save cssimsek/9019242 to your computer and use it in GitHub Desktop.
Function which removes all iframes present on a page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function iframeKilla() { | |
var iframeEls = document.getElementsByTagName("iframe"); | |
var iframeLength = iframeEls.length; | |
console.log(iframeEls.length); | |
while(iframeLength > 0) { | |
iframeEls[iframeLength - iframeLength].remove(); | |
console.log(iframeEls.length); | |
} | |
}; | |
iframeKilla(); | |
// the below cross-browser compatible version borrows James Padolsey's solution --> http://goo.gl/RGdmZ2 | |
function removeElement(element) { | |
element && element.parentNode && element.parentNode.removeChild(element); | |
} | |
function iframeKilla(removerFunc) { | |
var iframeEls = document.getElementsByTagName("iframe"); | |
var iframeLength = iframeEls.length; | |
if(iframeLength > 0) { | |
removerFunc(iframeEls[iframeLength - iframeLength]); | |
console.log("removing iframe:" + parseInt((iframeEls.length + 1), 10)); | |
iframeKilla(removerFunc); | |
} | |
else { | |
return console.log("no more iframes!!"); | |
} | |
}; | |
iframeKilla(removeElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Obviously this could be applied to any other tag. Also note that according to MDN ChildNode.remove() isn't supported in IE or Safari. So it would probably be best to apply the
element.parentNode.removeChild(element);
approach.I applied the cross-browser compatible approach using James Padolsey's function this time using recursion rather than a while loop.