How to remove only the parent element, without removing the children

Asked

Viewed 353 times

2

How to remove only the parent element, without also remove child elements with jQuery. Having this structure for example:

<a href="#">
    <p>A</p>
    <p>B</p>
    <p>C</p>
</a>

With the intention of removing the parent(), after the function the structure would look like this:

<p>A</p>
<p>B</p>
<p>C</p>

2 answers

3


Use the function unwrap() in jQuery.

For test purposes I have created a button that does the simulation.

$('.ativar').on('click', function(){
  if($('p').parent().is('a'))
    $('p').unwrap();
  else
    $('p').wrap('<a href="#"></a>');    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#">
  <p>A</p>
  <p>B</p>
  <p>C</p>
</a>

<button class="ativar">Ativar/Desativar</button>

  • Thank you very much!

2

Another alternative would be to take the content and replace it:

var children = $("a").contents();
$("a").replaceWith(children);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#">
    <p>A</p>
    <p>B</p>
    <p>C</p>
</a>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.