how to remove matched tags but leave content with JQuery

旧时模样 提交于 2019-12-31 00:57:10

问题


I have HTML like this:

<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:

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

However this is undefined. How would you do this?


回答1:


try

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



回答2:


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

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



回答3:


In jQuery you could also use contents and unwrap.

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


来源:https://stackoverflow.com/questions/2018050/how-to-remove-matched-tags-but-leave-content-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!