这是我的默认代码我希望使用js删除此div中的脚本,注释和一些文本,并在js mask后获取最终代码
我发现此代码删除脚本但它删除了我想从此div中删除的所有脚本
$('script').each(function () {
$(this).remove();
});
我的代码:
<div class="data-content">
<!-- comment_beginning -->- Sponsored Links -
<br>
<script src="//data.js"></script>
<!-- comment -->
<script>
//some js
</script>
<br>
- Sponsored Links -<!-- /comment_beginning -->
<div>
<a href="d.jpg"><img title="example" src="world.jpg" alt="data" width="300" class="animation-data-type0-2"></a>
</div>
<p></p>
<p></p>
<p></p>
<!-- comment_after -->- Sponsored Links -
<br>
<script src="//data.js"></script>
<!-- comment -->
<script>
//some js
</script><!-- /comment_after -->
</div>
最终输出:
<div class="data-content">
<div>
<a href="d.jpg"><img title="example" src="world.jpg" alt="data" width="300" class="animation-data-type0-2"></a>
</div>
<p></p>
<p></p>
<p></p></div>
答案 0 :(得分:1)
您可以使用以下代码来定位所提到的div下的所有脚本标记。
$(".data-content script").each(function(){
var scriptElement = $(this);
scriptElement.remove();
});
删除评论的代码:
var container = $(".data-content");
container.contents()
.filter(function(){ return this.nodeType == 8; })
.remove();
答案 1 :(得分:1)
使用$('.data-content').find('script')
仅选择script tags
。要删除注释,请遍历内容并删除,如下所示
$('.data-content').find('script').each(function () {
$(this).remove();
});
$('.data-content').contents().each(function() {
if(this.nodeType === Node.COMMENT_NODE) {
$(this).remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My code:
<div class="data-content">
<!-- comment_beginning -->- Sponsored Links -
<br>
<script src="//data.js"></script>
<!-- comment -->
<script>
//some js
</script>
<br>
- Sponsored Links -<!-- /comment_beginning -->
<div>
<a href="d.jpg"><img title="example" src="world.jpg" alt="data" width="300" class="animation-data-type0-2"></a>
</div>
<p></p>
<p></p>
<p></p>
<!-- comment_after -->- Sponsored Links -
<br>
<script src="//data.js"></script>
<!-- comment -->
<script>
//some js
</script><!-- /comment_after -->
</div>
答案 2 :(得分:0)
<强>解决强>
感谢文本仍然是他们的帮助,这就是我删除文本的方式
$(".data-content").contents().filter(function () {
return this.nodeType === 3; // Text nodes only
}).remove();