使用javascript去除文本节点周围的标签 [英] Remove tag around a text node using javascript

查看:74
本文介绍了使用javascript去除文本节点周围的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一些HTML如下所示:

 < div id =text> 
这是一些正在编写的文本< span class =highlight>其中
是突出显示的部分< / span>以及一些跟随它的文字。
< / div>

我想删除离开文本节点的span,我该如何去做那?我尝试使用jQuery来执行以下操作:

  wrap = $('。highlight'); 
wrap.children()。insertBefore(wrap);
wrap.remove();

但这不起作用我在猜测,因为儿童只会返回一个空集在那里的节点。所以发生的一切就是跨度和它的内容被删除。



我也在这里开放替代我的方法。发生什么事是我的代码实际上创建了一个用户选择文本块时的跨度。它将选定的文本包装在一个范围中以便在视觉上区分它。我需要删除后来的跨度,虽然因为mozilla的范围对象的工作方式的一些怪癖。编辑:我不想取代'#
$ b

的整个内容。文字,因为它可能非常大。

解决方案

您可以获得文本,并用它替换跨度:

  var wrap = $('。highlight'); 
var text = wrap.text();
wrap.replaceWith(text);


If I have some HTML that looks like this:

<div id="text">
      This is some text that is being written <span class="highlight">with
      a highlighted section</span> and some text following it.
</div>

And I want to remove the "span" leaving the text node within, how would I go about doing that? I tried using jQuery to do the following:

wrap = $('.highlight');
wrap.children().insertBefore(wrap);
wrap.remove();

But that doesn't work I'm guessing because children returns an empty set since there's only a text node in there. So all that happens is that the span and its contents are removed.

I'm also open to alternatives to my approach here. What's happening is that my code actually creates that span when a user selects a block of text. It wraps the selected text in a span to visually differentiate it. I need to remove the span afterward though because of some quirks with the way mozilla's range object works.

EDIT: I don't want to replace the entire content of '#text' by the way since it could be very large.

解决方案

You get the text, and replace the span with it:

var wrap = $('.highlight');
var text = wrap.text();
wrap.replaceWith(text);

这篇关于使用javascript去除文本节点周围的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆