繁体   English   中英

从特定的div删除脚本和html注释

[英]remove script and html comment from a specific div

这是我的默认代码,我想使用js从此div中删除脚本,注释和一些文本,并在js掩码后获取以下最终代码

我发现此代码删除脚本,但仅删除了我要从此div删除的所有脚本

$('script').each(function () {
$(this).remove();
});

我的代码:

<div class="data-content">         
        <!-- comment_beginning -->- Sponsored Links -
        &nbsp;
        <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 -
        &nbsp;
        <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>

您可以使用以下代码来定位位于上述div下的所有脚本标签。

  $(".data-content script").each(function(){
     var scriptElement = $(this);

     scriptElement.remove();
  });

删除注释的代码:

 var container = $(".data-content");

container.contents()
         .filter(function(){ return this.nodeType == 8; })
         .remove();

使用$('.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 - &nbsp; <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 - &nbsp; <br> <script src="//data.js"></script> <!-- comment --> <script> //some js </script><!-- /comment_after --> </div> 

解决了

感谢您的帮助,文字仍然是他们的,这就是我删除文字的方式

$(".data-content").contents().filter(function () {
        return this.nodeType === 3; // Text nodes only
    }).remove();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM