7

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?

8
  • Post your code...Because we cant guess what you are doing... Commented May 8, 2013 at 7:15
  • 3
    Googling "javascript remove all childs" for example should answer this question. Commented May 8, 2013 at 7:15
  • "javascript empty a div" finds this: stackoverflow.com/questions/3450593/… Commented May 8, 2013 at 7: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. Commented May 8, 2013 at 7:20
  • 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). Commented May 8, 2013 at 7:39

2 Answers 2

20

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Using myNode.lastChild instead of myNode.firstChild is usually faster.
@CedX can you explain why? or provide evidence?
@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. measurethat.net/Benchmarks/Show/3545/0/…
-2

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

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

$(".btn-post").html("")

8 Comments

The question is not how to determine if some div is empty. The question is how to empty it.
Now i changed my post Mr.Jan Dvorak
@Vinodhini : He want to clear the contents such as child node inside the div not the innerHTML.
yes that's why gave upvote for the answer. But the example is not clear. Thats what i mentioned
The question is to use raw js, not jquery.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.