Categories
JavaScript Answers

How to Remove Only the Parent Element and not its Child Elements in JavaScript?

Spread the love

To remove only the parent element and not its child elements in JavaScript, we can create a new fragment that has the element itself removed but with the children kept.

Then we can replace the element with the fragment which has the child elements.

For instance, if we have:

<div>  
  pre text  
  <div class="remove-just-this">  
    <p>child foo</p>  
    <p>child bar</p>  
    nested text  
  </div>  
  post text  
</div>

and we want to remove the div with class remove-just-this , then we can write:

const fragment = document.createDocumentFragment();  
const element = document.querySelector('.remove-just-this')  
while (element.firstChild) {  
  fragment.appendChild(element.firstChild);  
}  
element.parentNode.replaceChild(fragment, element);

We call document.createDocumentFragment to create a fragment.

Then we get the div with class remove-just-this with document.querySelector .

Then we get the children of the div and append them to the fragment with:

while (element.firstChild) {  
  fragment.appendChild(element.firstChild);  
}

And finally, we call element.parentNode.replaceChild to replace the element with the fragment .

Now we get:

<div>  
  pre text  
    
    <p>child foo</p>  
    <p>child bar</p>  
    nested text  
    
  post text  
</div>

as a result.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *