javaScript appendChild与removeChild平添、移除页面元素
javaScript appendChild与removeChild添加、移除页面元素
在JavaScript中使用appendChild()方法向页面元素中追加子对象和removeChild()方法从页面中移除对象,先看如下的HTML代码:
<body> <div id="nw"></div> <span id="ch"></span> </body>
一共有两个页面元素,现在我们想把id="ch"的span元素追加到div中,我们可以使用appendChild()方法来完成,如下:
document.getElementById('nw').appendChild(document.getElementById('ch'));
如果你使用的浏览器是火狐或Chrome,那么查看页面元素,你会发现span元素是div元素的子对象了,如果你用的不是火狐或Chrome,那么可以通过css来检测span现在是不是div元素的子对象。
现在再来介绍如何用removeChild()移除对象
<body> <div id="nw"><span id="ch"></span></div> </body>
div元素中包含子元素span,我们使用removeChild()将span标签移除
document.getElementByIdx_x('nw').removeChild(document.getElementByIdx_x('ch'));
使用firebug或css检测页面,发现span标签已经不存在了。
实践
代码如下:
<html> <head> <title>appendChild和removeChild</title> </head> <body> <div id="nw"></div> <span id="ch"></span> <input type="button" value="appendChild" onclick="appendChildMethod();" /> <input type="button" value="removeChild" onclick="removeChildMethod();" /> </body> </html> <script language="JavaScript" type="text/javascript"> function appendChildMethod() { document.getElementById('nw').appendChild(document.getElementById('ch')); } function removeChildMethod() { document.getElementById('nw').removeChild(document.getElementById('ch')); } </script>
运行结果:
打开页面,未点击按钮前:
点击“appendChild”按钮后:
进一步点击“removeChild”按钮后:
平时我们使用appendChild()一般是创建一个页面窗口,而使用removeChild()一般是从页面中移除页面窗口。