jQuery move child's child section element to its parent and remove other elements

Viewed 43

I have a parent-container which it has heading, other divs, and mainly <section>.

I want to move <section> alone to its parent in each container.

My code is running as expected, but I need to remove all other elements which comes dynamically, Eg: table, p, b etc... and I am not sure, is this the correct way to do it or not. :(

The final code should be in below format:

<div class="parent-container">
   <section>Original content 1</section>
</div>
<div class="parent-container">
   <section>Original content 2</section>
</div>
<div class="parent-container">
   <section>Original content 3</section>
</div>

jsFiddle

$('.parent-container').each(function () {
 jQuery(this).find('section').appendTo($(this));
 jQuery(this).find('div').remove();
 jQuery(this).find('h1').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="parent-container">
 <div class="pc-1">
  <h1>Hello world</h1>
  <div class="pc-2">
   <section>Original content 1</section>
   <p>Some more content</p>
  </div>
 </div>
</div>

<div class="parent-container">
 <div class="pc-1">
  <h1>Hello world</h1>
  <div class="pc-2">
   <section>Original content 2</section>
   <p>Some more content</p>
  </div>
 </div>
</div>

<div class="parent-container">
 <div class="pc-1">
  <h1>Hello world</h1>
  <div class="pc-2">
   <section>Original content 3</section>
   <p>Some more content</p>
  </div>
 </div>
</div>

2 Answers

After moving the <section> tags, select and remove anything that is not a <section>:

$('.parent-container').each(function () {
 jQuery(this).find('section').appendTo($(this)); // Move sections to parent
 jQuery(this).find(':not(section)').remove(); // Delete anything that is not a section
});

You can clone your section element and then remove all children from your parent div and then append your clone element to parent .

Demo Code :

$('.parent-container').each(function() {
  var clone_your_secction = jQuery(this).find('section').clone() //clone section
  jQuery(this).children().remove() //remove all childrens
  jQuery(clone_your_secction).appendTo($(this)); //append same
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="parent-container">
  <div class="pc-1">
    <h1>Hello world</h1>
    <div class="pc-2">
      <section>Original content 1</section>
      <p>Some more content</p>
    </div>
  </div>
</div>

<div class="parent-container">
  <div class="pc-1">
    <h1>Hello world</h1>
    <div class="pc-2">
      <section>Original content 2</section>
      <p>Some more content</p>
    </div>
  </div>
</div>

<div class="parent-container">
  <div class="pc-1">
    <h1>Hello world</h1>
    <div class="pc-2">
      <section>Original content 3</section>
      <p>Some more content</p>
    </div>
  </div>
</div>

Related