如何删除匹配的标签,而将内容留给JQuery

时间:2022-10-27 14:16:54

I have HTML like this:

我有这样的HTML:

<div>
 <div class="a">
  content1
 </div>
 content 2
 <div class="a">
  <b>content 3</b>
 </div>
</div>

and I want to get rid of the div's of class="a" but leave their content. My initial attempt was:

我想去掉class="a"的div但是留下它们的内容。我最初的意图是:

$("div.a").replaceWith($(this).html());

However this is undefined. How would you do this?

然而这是未定义的。你会怎么做?

3 个解决方案

#1


8  

try

试一试

$("div.a").each(function(){
    $(this).replaceWith($(this).html());
});

#2


5  

Replacing elements with their stringified HTML content will nuke any event handlers that might be in place. This won't:

用其字符串化的HTML内容替换元素将使可能存在的任何事件处理程序失效。这不会:

$("div.a").each(function () {
    $(this).replaceWith($(this.childNodes));
});

#3


0  

In jQuery you could also use contents and unwrap.

在jQuery中,您还可以使用内容和展开。

$(".parent").find(".a").contents().unwrap(); 
<div class="parent">
 <div class="a">
  content1
 </div>
 content 2
 <div class="a">
  <b>content 3</b>
 </div>
</div>

#1


8  

try

试一试

$("div.a").each(function(){
    $(this).replaceWith($(this).html());
});

#2


5  

Replacing elements with their stringified HTML content will nuke any event handlers that might be in place. This won't:

用其字符串化的HTML内容替换元素将使可能存在的任何事件处理程序失效。这不会:

$("div.a").each(function () {
    $(this).replaceWith($(this.childNodes));
});

#3


0  

In jQuery you could also use contents and unwrap.

在jQuery中,您还可以使用内容和展开。

$(".parent").find(".a").contents().unwrap(); 
<div class="parent">
 <div class="a">
  content1
 </div>
 content 2
 <div class="a">
  <b>content 3</b>
 </div>
</div>