Remove all the children DOM elements in div

Remove all the children DOM elements in div

I have the following dojo codes to create a surface graphics element under a div:
….

….

….

drawRec() will draw a rectangle graphics first time. If I call this function again in an anchor href like this:

it will draw another graphics again. What I need to clean all the graphics under the div and then create again. How can I add some dojo codes to do that?

Solutions/Answers:

Solution 1:

while (node.hasChildNodes()) {
    node.removeChild(node.lastChild);
}

Solution 2:

node.innerHTML = "";

Non-standard, but fast and well supported.

Solution 3:

First of all you need to create a surface once and keep it somewhere handy. Example:

var surface = dojox.gfx.createSurface(domNode, widthInPx, heightInPx);

domNode is usually an unadorned <div>, which is used as a placeholder for a surface.

You can clear everything on the surface in one go (all existing shape objects will be invalidated, don’t use them after that):

surface.clear();

All surface-related functions and methods can be found in the official documentation on dojox.gfx.Surface. Examples of use can be found in dojox/gfx/tests/.

Solution 4:

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

Solution 5:

In Dojo 1.7 or newer, use domConstruct.empty(String|DomNode):

require(["dojo/dom-construct"], function(domConstruct){
  // Empty node's children byId:
  domConstruct.empty("someId");
});

In older Dojo, use dojo.empty(String|DomNode) (deprecated at Dojo 1.8):

dojo.empty( id or DOM node );

Each of these empty methods safely removes all children of the node.

Solution 6:

From the dojo API documentation:

dojo.html._emptyNode(node);
Related:  Array.length vs arrayinstance.length in javascript