3

Hey how do I remove all divs from a parent div in JavaScript?

I can't find non jquery examples. They all have different classes/Ids so I'm wondering if there is a simple way to do it ? For example:

<div id="parent">
   <div class="something"      id="one">Remove me</div>
   <div class="something_two"  id="two">Remove me</div>
   <div class="something_three"id="three">Remove me</div>
   <div class="something_four" id="four">Remove me</div>
</div>

Is there a simple way to do this - my current method is to do innerHTML = ""; but wondered if thats only best for removing text and not elements?

Sir
  • 7,905
  • 16
  • 79
  • 144

2 Answers2

9

Using innerHTML will remove actual elements, there are some cross browser quirks (mainly IE which, ironically, was the one that originally invented innerHTML).

Here's a more standard way of doing it:

var el = document.getElementById('parent');

while ( el.firstChild ) el.removeChild( el.firstChild );
Joseph Silber
  • 205,539
  • 55
  • 352
  • 286
3

The fastest way seems to be:

document.getElementById('parent').textContent = '';
Wojciech Bednarski
  • 5,509
  • 8
  • 47
  • 72