jQuery remove tags either side of a div

2019-08-29 09:22发布

问题:

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.

回答1:

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

$("div.test").unwrap();


回答2:

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



回答3:

Try the following:

$('.salon-slideshow').each(function() {
  $(this).parent().replaceWith($(this));
});


回答4:

Try this:

$('.test').each(function() {
    $(this).insertAfter($(this).parent());
    $(this).prev().remove();
});