JS - 删除标记而不删除内容

时间:2012-03-24 01:54:35

标签: javascript jquery

我想知道是否可以移除标签但是保留内容?例如,是否可以删除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标记。我将创建另一个问题来尝试解决我的问题。

9 个答案:

答案 0 :(得分:8)

<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);

答案 1 :(得分:6)

jQuery有更简单的方法:

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

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

答案 2 :(得分:2)

有几种方法可以做到这一点。 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>", "");

答案 3 :(得分:1)

它只是三个文本节点而不是一个。它没有明显的区别吗?

如果这是一个问题,请使用DOM normalize方法将它们组合起来:

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

答案 4 :(得分:1)

$(function(){

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

});​

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

答案 5 :(得分:0)

如果你不是在寻找一个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
}

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

祝你好运。

答案 6 :(得分:0)

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

假设我们有:

<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();
});

答案 7 :(得分:0)

如果这是父级中唯一的子跨度,则可以执行以下操作:

HTML:

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

JavaScript:

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

因此,只需将元素的HTML替换为其文本即可。

答案 8 :(得分:0)

您可以删除 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

相关问题