Remove all the children DOM elements in div

2019-01-07 06:05发布

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

....
<script type=text/javascript>
....
   function drawRec(){
      var node = dojo.byId("surface");
      //   remove all the children graphics
      var surface = dojox.gfx.createSurface(node, 600, 600);

      surface.createLine({
         x1 : 0,
         y1 : 0,
         x2 : 600,
         y2 : 600
      }).setStroke("black");
   }
....
</script>
....
<body>
<div id="surface"></div>
....

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

 <a href="javascript:drawRec();">...</a>

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?

7条回答
等我变得足够好
2楼-- · 2019-01-07 06:45

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/.

查看更多
看我几分像从前
3楼-- · 2019-01-07 06:48
while(node.firstChild) {
    node.removeChild(node.firstChild);
}
查看更多
别忘想泡老子
4楼-- · 2019-01-07 06:53

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.

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-07 06:55
while (node.hasChildNodes()) {
    node.removeChild(node.lastChild);
}
查看更多
别忘想泡老子
6楼-- · 2019-01-07 06:57
node.innerHTML = "";

Non-standard, but fast and well supported.

查看更多
相关推荐>>
7楼-- · 2019-01-07 07:02

From the dojo API documentation:

dojo.html._emptyNode(node);
查看更多
登录 后发表回答