仅使用JavaScript删除iframe脚本标记
我有一个自动生成的iframe(它也有一个类名,在同一个域上),里面还有一个仅使用JavaScript删除iframe脚本标记,javascript,html,Javascript,Html,我有一个自动生成的iframe(它也有一个类名,在同一个域上),里面还有一个标记和一些样式。有人能告诉我如何使用纯javascript删除脚本标记及其内容吗?[请不要使用jQuery请使用VueJS] <html> <body> <iframe src="#" class="myiframe"> #document <html> <body>
标记和一些样式。有人能告诉我如何使用纯javascript删除脚本标记及其内容吗?[请不要使用jQuery请使用VueJS]
<html>
<body>
<iframe src="#" class="myiframe">
#document
<html>
<body>
<!-- REMOVE-->
<style>...</style>
<!-- REMOVE-->
<div class="wrapper">...</div>
</body>
</html>
</iframe>
</body>
</html>
您可以尝试使用以下代码,此代码可能很长,让我们尝试并优化它:
<html>
<head>
<script>
function removeStyleTag() {
var iframe = document.getElementById("myFrame");
var styleTag = iframe.contentWindow.document.getElementsByTagName("style");
for (var index = styleTag.length - 1; index >= 0; index--) {
styleTag[index].parentNode.removeChild(styleTag[index]);
}
}
</script>
</head>
<body>
<iframe id="myFrame" src="#" class="myiframe">
#document
<html>
<body>
<!-- REMOVE-->
<style>...</style>
<!-- REMOVE-->
<div class="wrapper">...</div>
</body>
</html>
</iframe>
<button onclick="removeStyleTag()">Try It</button>
</body>
</html>
是一个链接,指向我在哪里尝试过这段代码的Fiddle。@code\u忍者可以使用JQuery,我已经看到了StackOverflow上的Q&a。为什么不使用Javascripts呢?是的,我刚刚找到了一种方法,让我们试着与您分享解决方案。不管怎样,iframe没有ID,我使用了
getElementsByClassName(“myiframe”)[0]
,它成功了!由于此iframe仅包含一个样式标记(可能选择第一个),因此有任何方法对其进行优化。它对我不起作用,您的styleTag
是一个空的HTMLCollection
@Armel,如果您试图在stackoverflow上使用它,则会出现此错误,因为我猜stackoverflow限制了外部源在这里运行iFrame。但是试一下小提琴,它会起作用的。@stackminu,是的,它会被转换成通用代码,但代码长度会增加,你能做到吗。。这是一个很好的选择,这在隐姓埋名或清除缓存,可能是由于这一点,工程为我和@stackminu每次
<html>
<head>
<script>
function removeStyleTag() {
var iframe = document.getElementById("myFrame");
var styleTag = iframe.contentWindow.document.getElementsByTagName("style");
for (var index = styleTag.length - 1; index >= 0; index--) {
styleTag[index].parentNode.removeChild(styleTag[index]);
}
}
</script>
</head>
<body>
<iframe id="myFrame" src="#" class="myiframe">
#document
<html>
<body>
<!-- REMOVE-->
<style>...</style>
<!-- REMOVE-->
<div class="wrapper">...</div>
</body>
</html>
</iframe>
<button onclick="removeStyleTag()">Try It</button>
</body>
</html>
var iframe = document.getElementById("myFrame");
var styleTag = iframe.contentWindow.document.getElementsByTagName("style");