且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-05 10:44:52

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

You can create a function/plugin that will recurse through elements in your top level element, removing any text nodes found:

$.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

参考:

  • .contents()
  • .each()
  • .remove()