【问题标题】:Remove all text content from HTML div but keep HTML tags and structure从 HTML div 中删除所有文本内容,但保留 HTML 标记和结构
【发布时间】:2015-11-21 17:52:51
【问题描述】:

我有:

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

我想要:

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

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

【问题讨论】:

  • 你可以使用:.empty()

标签: javascript jquery html dom


【解决方案1】:

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

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

参考:

【讨论】:

    【解决方案2】:

    显然您想从元素中删除所有文本节点。您可以使用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>

    【讨论】:

    • 可能是最简单最干净的方法!在第二个正确答案后几分钟。 :)
    【解决方案3】:

    纯javascript,递归解决方案:

    function removeAllText(element) {
    
        // loop through all the nodes of the element
        var nodes = element.childNodes;
    
        for(var i = 0; i < nodes.length; i++) {
    
            var node = nodes[i];
    
            // if it's a text node, remove it
            if(node.nodeType == Node.TEXT_NODE) {
    
                node.parentNode.removeChild(node);
    
    
                i--; // have to update our incrementor since we just removed a node from childNodes
    
            } else
    
            // if it's an element, repeat this process
            if(node.nodeType == Node.ELEMENT_NODE) {
    
                removeAllText(node);
    
            }
        }
    }
    

    像这样使用它:

    var thing = document.getElementById('thing');
    removeAllText(thing);
    

    很简单

    【讨论】:

    • 我不知道你为什么被否决...这是最好的答案
    • 不知道谁以及为什么反对它。然而,这并不能解决整个问题。您还需要删除世界Herebe removed。 :)
    • @DontVoteMeDown 那么他可以遍历childNodes吗?这是一个干净的、普通的 js 解决方案。
    • 我的意思是,他可以添加id,OP的代码根本没有id。他就像..没有迭代..
    • developer.mozilla.org/en-US/docs/Web/API/Node/textContent IE9+,以及每个版本的 Chrome、FF、Safari 和 Opera。所以,是的,相当不错。
    【解决方案4】:

    另一种方法,仅用于娱乐和学习目的。尝试在不使用原生 JS 函数、检查元素属性的情况下做到这一点......令人惊讶的是,它可以工作。

    clones=[];
    
    $('div').children().each(function() {
    
    clones.push($(this).clone().text(''));
    });
    
    $('div').empty();
    
    for(i=0;i<clones.length;i++) {
    
     clones[i].appendTo('div');
    }
    

    JQuery 不会将纯文本节点算作容器的子元素,因此我们也可以使用这种行为。

    演示:http://jsfiddle.net/djvhxgm9/

    【讨论】:

      【解决方案5】:
      function RemoveText(el){
         el.children().each(function(){
           var $this = $(this);
           if ($this.children().length > 0){
             $this.children().each(RemoveText($this));
           }
           else{
             $this.text("");
           }     
         });
      }
      

      【讨论】:

      • 使用.text("") 而不是empty()。 empty() 用于删除元素,而不是文本内容。
      • 将进行编辑,同时检查我们是否有子元素可以进行递归
      【解决方案6】:

      尝试:

      function empty(e) {
          var childs = e.children;
          for(var i=0;i<childs.length;i++) {
              if(childs[i].children.length!=0) {
                  childs[i].innerHTML=" ";
              } else {
                  empty(childs[i]);
              }
          }
      }
      

      【讨论】:

        【解决方案7】:

        检查当前节点有零个childNodes并且nodeType等于3然后将textContent设置为空字符串

        const removeAllInnerText = (element) => {
          const nodes = element.childNodes;
        
          nodes.forEach((node) => {
            if (node.nodeType === Node.ELEMENT_NODE && node.childNodes.length > 0) {
              removeAllInnerText(node);
            } else if (node.nodeType === Node.TEXT_NODE) {
              node.textContent = "";
            }
          });
        };
        
        const container = document.querySelector(".container");
        removeAllInnerText(container);
        <!DOCTYPE html>
        <html lang="en">
          <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <script defer src="./index.js"></script>
            <title>Document</title>
          </head>
          <body>
            <div class="container">
              Here
              <a href="#"> is </a>
              <p>Text, that I want to</p>
              be removed
            </div>
          </body>
        </html>

        【讨论】:

          【解决方案8】:

          使用 jquery .empty() 方法

          https://api.jquery.com/empty/

          示例:

          <!--input-->
          <div class="container">
            <div class="hello">Hello</div>
            <div class="goodbye">Goodbye</div>
          </div>
          
          $( ".hello" ).empty();
          
          <!--result-->
          <div class="container">
            <div class="hello"></div>
            <div class="goodbye">Goodbye</div>
          </div>
          

          【讨论】:

          • 它也会删除子元素。
          猜你喜欢
          • 2014-03-11
          • 2011-06-05
          • 2011-05-13
          • 2015-10-12
          • 2014-03-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多