时间:2021-07-01 10:21:17 帮助过:7人阅读
1. 概述
删除后的节点虽然不在文档树中了,但其实它还在内存中,可以随时再次被添加到别的位置。
当你遍历一个父节点的子节点并进行删除操作时,要注意,children属性是一个只读属性,并且它在子节点变化时会实时更新
- // 拿到待删除节点:
- var self = document.getElementById('to-be-removed');
- // 拿到父节点:
- var parent = self.parentElement;
- // 删除:
- var removed = parent.removeChild(self);
- removed === self; // true
2. example
- <!DOCTYPE html>
- <html>
- <head>
- </script>
- </head>
- <body>
- <ul id="test-list">
- <li>JavaScript</li>
- <li>Swift</li>
- <li>HTML</li>
- <li>ANSI C</li>
- <li>CSS</li>
- <li>DirectX</li>
- </ul>
- <script>
- var p= document.getElementById('test-list');
- var length = p.children.length;
- var i=0;
- for(; i<length; ){
- var li = p.children[i];
- var text = li.innerText;
- if(text!=='JavaScript' && text!=='HTML' && text!=='CSS'){
- p.removeChild(li);
- alert(p.children.toString());
- length--;
- }else{
- i++;
- }
- }
- // 测试:
- ;(function () {
- var
- arr, i,
- t = document.getElementById('test-list');
- if (t && t.children && t.children.length === 3) {
- arr = [];
- for (i = 0; i < t.children.length; i ++) {
- arr.push(t.children[i].innerText);
- }
- if (arr.toString() === ['JavaScript', 'HTML', 'CSS'].toString()) {
- alert('测试通过!');
- }
- else {
- alert('测试失败: ' + arr.toString());
- }
- }
- else {
- alert('测试失败!');
- }
- })();
- </script>
- </body>
- </html>
以上所述是小编给大家介绍的JavaScript中removeChild 方法开发示例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!