jqueryhtmldomunwarp

jQuery unwrap removing more than one parent


I have an html structure like so

<aside class="l-region l-region--sidebar-first">
  <div></div>
  <div></div>
</aside>

The two divs inside the aside do have classes and child elements but for the sake of the question you don't need to know what they are. On DOM ready, I wrap the two inner divs in a new div like so

<aside class="l-region l-region--sidebar-first">
  <div class"wrapping-div">  
    <div class="inner-div-one"></div>
    <div class="inner-div-two"></div>
  </div>
</aside>

I don't use the wrap() function to get the two divs inside .wrapping-div, I create that div, append it to the DOM inside the aside and then append the two inner divs to that new element I created.

When I try to unwrap() those two divs, both .wrapping-div and .l-region--sidebar-first are removed from the DOM. JS to unwrap the elements below.

$(function() {
  $('.inner-div-one').unwrap();
  $('.inner-div-two').unwrap();
});

I thought that unwrap() was supposed to remove one parent. Why is it removing both and does anyone know how I can stop this?

Cheers.


Solution

  • your code is actually working as it is expected to work. As at first instance of $('.inner-div-one').unwrap(); you are removing the parent div and at second instance you are removing aside tag. It is actually removing only one parent at a time. I think you don't need the second statement over there.