Is it possible to remove an html element and keep your children with javascript?

wDrik :

I have the following structure .. I would like to remove div.son but keepdiv.grandson, is that possible ?! or changing your <tag> would also be a solution .. ex: changing from <fieldset> to a <div>, remembering that I do not have access to HTML, every change must be done using ** javascript **!

<div class="father">
  <fieldset class="son">
    <div class="grandson">Content here</div>
    <div class="grandson">Content here</div>
    <div class="grandson">Content here</div>
    <div class="grandson">Content here</div>
  </fieldset>
</div>

I tried to use the removeChild () function of ** javascript **, but it removes the entire element.

Samuli Hakoniemi :

It's possible with vanilla JavaScript by deep cloning the node of grandson before removing anything else. and then appending it back to the parent. Of course if you want to place it somewhere else, you need to append needed logic of DOM traversing. (CSS section is only for visual validation of the result)

const grandson = document.querySelector('.grandson');
const father = grandson.closest('.father');
const clonedGrandson = grandson.cloneNode(true);

father.querySelector('.son').remove();
father.appendChild(clonedGrandson);
.father {
  background-color: red;
  padding: 20px;
 }
 
 .son {
  background-color: blue;
  padding: 20px;
 }
 
 .grandson {
  background-color: green;
  padding: 20px;
 }
<div class="father">
  <fieldset class="son">
    <div class="grandson">
      <p>Save me</p>
    </div>
  </fieldset>
</div>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31919&siteId=1