6

I found some jQuery code to clear the contents of a div:

$('#masterdiv').empty();

Is there any similar way to do this in raw javascript, without jQuery or any other library?

TRiG
  • 10,148
  • 7
  • 57
  • 107
Max25
  • 587
  • 2
  • 5
  • 16
  • Post your code...Because we cant guess what you are doing... – 웃웃웃웃웃 May 08 '13 at 07:15
  • 3
    Googling "javascript remove all childs" for example should answer this question. – Denys Séguret May 08 '13 at 07:15
  • "javascript empty a div" finds this: http://stackoverflow.com/questions/3450593/how-to-clear-the-content-of-a-div-using-javascript – John Dvorak May 08 '13 at 07:17
  • @dreamweiver there's nothing wrong with not wanting to use jQuery. "Educational purposes" is a valid reason. "extremely ligthweight (and we don't trust the browser's cache)" is another. – John Dvorak May 08 '13 at 07:20
  • I'f you're wondering why you've been downvoted: obvious lack of research, supported by "I need code". Poor grammar doesn't help either. – John Dvorak May 08 '13 at 07:24
  • Instead of downvoting just guide him on do's and dont's. It may help him tom avoid such things in future. – Praveen Singh May 08 '13 at 07:34
  • 2
    @praveensingh it's not "instead of downvoting". It's "as well as downvote (and remove the vote if the question improves enough)". If there are only minor mistakes to fix, downvotes are not needed. Lack of research cannot be fixed, and this question won't be useful as a search target for a duplicate, either, I'm afraid (since a duplicate with the same keywords already exists). – John Dvorak May 08 '13 at 07:39
  • Theres nothing really wrong with this question. Theres lots of ways to achieve the above jquery result. – Kevin Brydon Jun 17 '20 at 11:45

2 Answers2

19

This code will work.

while (myNode.firstChild) {
    myNode.removeChild(myNode.firstChild);
}

Mention the id of the tag on myNode for which you want to remove the inner child.

Praveen Singh
  • 534
  • 2
  • 8
  • 23
  • 2
    Using `myNode.lastChild` instead of `myNode.firstChild` is usually faster. – CedX Jun 30 '20 at 13:36
  • @CedX can you explain why? or provide evidence? –  Jun 14 '21 at 22:30
  • 2
    @cakelover The DOM reflow is less important with `lastChild`. Imagine a stack of coins: `firstChild` is at the bottom, `lastChild` is at the top. It is easier to remove the top coin than the bottom one. https://www.measurethat.net/Benchmarks/Show/3545/0/innerhtml-vs-removechildfirstchild-vs-removechildlastch – CedX Jun 16 '21 at 08:04
-2

Please have a look on http://jsfiddle.net/2dJAN/19/

<div class="btn-post">123</div>   

$(".btn-post").html("")
vinothini
  • 2,606
  • 4
  • 27
  • 42