从 HTML div 中删除所有文本内容,但保留 HTML 标签和结构

新手上路,请多包涵

我有:

 <div>
    Here
    <a href="#"> is </a>
    <p> Text, that I want to </p>
    be removed
</div>

我想:

 <div>
    <a href="#"> </a>
    <p> </p>
</div>

删除所有文本但保留 HTML 结构的最简单方法是什么?

原文由 Lokomotywa 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 433
2 个回答

您可以创建一个函数/插件,它将递归遍历顶级元素中的元素,删除找到的任何文本节点:

 $.fn.removeText = function(){
  this.each(function(){

     // Get elements contents
     var $cont = $(this).contents();

      // Loop through the contents
      $cont.each(function(){
         var $this = $(this);

          // If it's a text node
          if(this.nodeType == 3){
            $this.remove(); // Remove it
          } else if(this.nodeType == 1){ // If its an element node
            $this.removeText(); //Recurse
          }
      });
  });
}

$('#toplevel').removeText();

JSFiddle

参考:

原文由 George 发布,翻译遵循 CC BY-SA 3.0 许可协议

显然您想从元素中删除所有文本节点。您可以使用 jQuery.contents 函数访问文本节点。而且您不需要任何递归。 jQuery 为你做了:

 $(function() {
  $("#to-clean, #to-clean *")                  // selects the element and all element nodes inside it
    .contents()                                // selects all child nodes including tags, comments and text
    .filter(function() {
      return this.nodeType === Node.TEXT_NODE; // filter text nodes
    }).remove();                               // boom!
});
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="to-clean">
  Here
  <a href="#"> is </a>
  <p>Text, that I want to</p>
  be removed
</div>

原文由 Salman A 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题