jQuery remove tags either side of a div

2019-08-29 09:01发布

How can I remove the p tags outside of this div (I do not want to remove the test div).

<p>
  <div class='test'>
    content here
    <img />
  </div>
</p>

The result I'd like would be...

<div class='test'>
  content here
  <img />
</div>

I know there's a similar question here: jQuery: How do I remove surrounding div tags?, but not got it to work in my situation

I've tried

$('p .test').replaceWith($('.test));

But of course that just selects the salon-slideshow div, rather than the p before it.

4条回答
Luminary・发光体
2楼-- · 2019-08-29 09:03

Try this:

$('.test').each(function() {
    $(this).insertAfter($(this).parent());
    $(this).prev().remove();
});
查看更多
一夜七次
3楼-- · 2019-08-29 09:04

Try the following:

$('.salon-slideshow').each(function() {
  $(this).parent().replaceWith($(this));
});
查看更多
手持菜刀,她持情操
4楼-- · 2019-08-29 09:08

The method you are looking for is called .unwrap() check out the documentation : http://api.jquery.com/unwrap/

查看更多
我想做一个坏孩纸
5楼-- · 2019-08-29 09:12

This will do it but remember that it will affect all divs with class="test"

$("div.test").unwrap();
查看更多
登录 后发表回答