Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 639
Ao C Avatar asked Jan 05 '23 12:01

Ao C


1 Answers

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>
like image 97
Michał Perłakowski Avatar answered Jan 13 '23 10:01

Michał Perłakowski