Home > Back-end >  Delete only div containers inside a container
Delete only div containers inside a container

Time:01-11

The aim is to delete all div containers within a container and leave two anhchor tags untouched.

<div id="container">
  <div id="wrapper" >

    <div><img src=""></div>
    <div><img src=""></div>
    <div><img src=""></div>

    <!-- Next and previous buttons -->
    <a  onclick="plusSlides(-1)">&#10094;</a>
    <a  onclick="plusSlides(1)">&#10095;</a>

  </div>
</div>

expected / goal

<div id="container">
  <div id="wrapper" >
    <!-- Next and previous buttons -->
    <a  onclick="plusSlides(-1)">&#10094;</a>
    <a  onclick="plusSlides(1)">&#10095;</a>

  </div>
</div>

With innerHTML everything is deleted and therefore also the a tags. Is there an elegant and simple solution?

CodePudding user response:

Use the remove method to remove an element from the DOM.

document.querySelectorAll("#wrapper > div").forEach(el => el.remove());

CodePudding user response:

You can use querySelectorAll to find all div blocks:

let container = document.getElementById("wrapper");
container.querySelectorAll("div").forEach(e => e.remove());

Note: I haven't tested this on a document with nested divs. Since then one div could get deleted before it is iterated in the loop it may cause problems. And additional check or repeating querySelectorAll until none are found should solve that problem.

  •  Tags:  
  • Related