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?

4

2 に答える 2

8

innerHTML willを使用すると、実際の要素が削除されます。クロスブラウザの癖がいくつかあります(主にIEは、皮肉なことに、最初に発明されたものでしたinnerHTML)。

これを行うためのより標準的な方法は次のとおりです。

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

while ( el.firstChild ) el.removeChild( el.firstChild );
于 2013-01-28T03:54:52.627 に答える
2

最速の方法は次のようです:

document.getElementById('parent').textContent = '';
于 2013-01-28T04:13:47.100 に答える