【问题标题】:JS - Remove a tag without deleting contentJS - 删除标签而不删除内容
【发布时间】:2012-04-08 13:26:19
【问题描述】:

我想知道是否可以删除标签但保持内容完整?例如,是否可以删除 SPAN 标记但保留 SPAN 的内容?

<p>The weather is sure <span>sunny</span> today</p> //original

<p>The weather is sure sunny today</p> //turn it into this

我曾尝试使用 this 使用 replaceWith() 的方法,但它把 HTML 变成了

<p>
  "The weather is sure " 
  "sunny"
  " today"
</p>

编辑:在测试了你所有的答案后,我意识到我的代码有问题。我不断得到三个拆分文本节点的原因是由于插入了 SPAN 标记。我将创建另一个问题来尝试解决我的问题。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

它只是三个文本节点而不是一个。它不会产生明显的差异吗?

如果有问题,使用 DOM normalize 方法将它们组合起来:

$(...)[0].normalize();

【讨论】:

  • 是的,这对我的目的有所不同。我正在存储原始的 DOM 结构。使用 replaceWith() 会稍微改变 DOM 结构,所以我的代码现在崩溃了 :(
【解决方案2】:
$(function(){

   var newLbl=$("p").clone().find("span").remove().end().html();
    alert(newLbl);

});​

例如:http://jsfiddle.net/7gWdM/6/

【讨论】:

    【解决方案3】:

    有几种方法可以做到这一点。 jquery是最简单的方法:

    //grab and store inner span html
    var content = $('p span').html;
    //"Re"set inner p html
    $('p').html(content);
    

    Javascript 可以使用 element.replace 来做同样的事情。 (我不记得用正则表达式一次性完成替换,但这是最简单的方法)

    paragraphElement.replace("<span>", "");
    paragraphElement.replace("</span>", "");
    

    【讨论】:

      【解决方案4】:

      jQuery 有更简单的方法:

      var spans = $('span');
      spans.contents().unwrap();
      

      使用不同的选择器方法,可以删除深度嵌套的 span 或仅删除元素的直接子 span。

      【讨论】:

        【解决方案5】:
        <p>The weather is sure <span>sunny</span> today</p>;
        
        
        var span=document.getElementsByTagName('span')[0]; // get the span
        var pa=span.parentNode;
        while(span.firstChild) pa.insertBefore(span.firstChild, span);
        
        pa.removeChild(span);
        

        【讨论】:

          【解决方案6】:

          如果您不是在寻找 jQuery 解决方案,这里有一些更轻量级且专注于您的场景的解决方案。

          我创建了一个名为getText() 的函数并递归地使用它。简而言之,您可以获得p 元素的子节点并检索该p 节点内的所有文本节点。

          DOM 中的几乎所有东西都是某种节点。查看以下链接,我发现文本节点的数字 nodeType 值为 3,当您确定文本节点的位置时,您会得到它们的 nodeValue 并将其返回以连接到整个非文本-无节点值。

          https://developer.mozilla.org/en/nodeType

          https://developer.mozilla.org/En/DOM/Node.nodeValue

          var para = document.getElementById('p1')  // get your paragraphe 
          var texttext = getText(para);             // pass the paragraph to the function
          para.innerHTML = texttext                 // set the paragraph with the new text
          
          function getText(pNode) {
          
              if (pNode.nodeType == 3) return pNode.nodeValue;
          
              var pNodes = pNode.childNodes        // get the child nodes of the passed element
              var nLen = pNodes.length             // count how many there are
              var text = "";
          
              for (var idx=0; idx < nLen; idx++) {   // loop through the child nodes
                  if (pNodes[idx].nodeType != 3 ) {  // if the child not isn't a text node
                      text += getText(pNodes[idx]);  // pass it to the function again and 
                                                     // concatenate it's value to your text string  
                  } else {
                      text += pNodes[idx].nodeValue  // otherwise concatenate the value of the text
                                                     // to the entire text
                  }
          
              }
          
              return text
          }
          

          我尚未针对所有情况对此进行测试,但它适用于您目前正在做的事情。它比替换字符串稍微复杂一些,因为您正在寻找文本节点而不是硬编码来删除特定标签。

          祝你好运。

          【讨论】:

            【解决方案7】:

            如果有人仍在寻找,对我有用的完整解决方案是:

            假设我们有:

            <p>hello this is the <span class="highlight">text to unwrap</span></p>
            

            js 是:

            // get the parent
            var parentElem = $(".highlight").parent(); 
            
            // replacing with the same contents
            $(".highlight").replaceWith( 
                function() { 
                    return $(this).contents();
                }
            );
            
            // normalize parent to strip extra text nodes
            parentElem.each(function(element,index){
                $(this)[0].normalize();
            });
            

            【讨论】:

              【解决方案8】:

              如果它是父类中唯一的子跨度,你可以这样做:

              HTML:

              <p class="parent">The weather is sure <span>sunny</span> today</p>;
              

              JavaScript:

              parent = document.querySelector('.parent');
              parent.innerHTML = parent.innerText;
              

              所以只需将元素的 HTML 替换为其文本即可。

              【讨论】:

                【解决方案9】:

                您可以删除 span 元素并保持 HTML 内容或内部文本不变。使用 jQuery 的 unwrap() 方法。

                    <html>
                      <head>
                        <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
                        <script type="text/javascript">
                          $(document).ready(function(){
                            $("button").click(function(){
                              $("p").find("span").contents().unwrap();
                            });
                          });
                        </script>
                      </head>
                      <body>
                        <p>The weather is sure <span style="background-color:blue">sunny</span> today</p>
                        <button type="button">Remove span</button>
                      </body>
                    </html>

                您可以在此处查看示例:How to remove a tag without deleting its content with jQuery

                【讨论】:

                  猜你喜欢
                  • 2012-09-29
                  • 1970-01-01
                  • 2016-04-16
                  • 1970-01-01
                  • 1970-01-01
                  • 2020-07-23
                  • 1970-01-01
                  • 1970-01-01
                  • 2019-04-09
                  相关资源
                  最近更新 更多