Ao C Ao C - 3 months ago 9
Javascript Question

Move HTML children elements out of parent and remove the parent element

Trying to move children outside of parent then remove the parent itself in vanilla JavaScript. Current code looks something like this:

<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>


Desired output:

<div class="child"></div>
<div class="child"></div>

Answer

Try setting outerHTML property to innerHTML property.

const parent = document.querySelector('.parent')
parent.outerHTML = parent.innerHTML

See live demo:

console.log('Before change: ', document.querySelector('.container').innerHTML)

const parent = document.querySelector('.parent')
parent.outerHTML = parent.innerHTML

console.log('After change: ', document.querySelector('.container').innerHTML)
<div class="container">
  <div class="parent">
    <div class="child"></div>
    <div class="child"></div>
  </div>
</div>

Comments