DOM结构操作

  • 新增节点
  1. var div1 = document.getElementById('div1');
  2. //添加新节点
  3. var p1 = document.createElement('p');
  4. p1.innerHTML = 'this is p1';
  5. div1.appendChild(p1); //添加新创建的元素
  6. //移除已有节点
  7. var p2 = document.getElementById('p2');
  8. div1.appendChild(p2);
  • 获取父元素-获取子节点
  1. var div1 = document.getElementById('div1');
  2. var parent = div1.parentElement;
  • 删除节点
  1. var div1 = document.getElementById('div1');
  2. var child = div1.childNodes;
  3. div1.removeChild(child[0]);

举个栗子(例子:example)!!!

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. </head>
  5. <body>
  6. <div id="div1">
  7. <p id="p1">this is p1</p>
  8. <p id="p2">this is p2</p>
  9. </div>
  10. <div id="div2">
  11. <p id="p3">this is p3</p>
  12. <p id="p4">this is p4</p>
  13. </div>
  14. <script type="text/javascript">
  15. // 1.
  16. // var p = document.createElement('p');
  17. // p.innerHTML = 'new p';
  18. // var div1 = document.getElementById('div1');
  19. // div1.appendChild(p);
  20. // 2.移动P4到div1中
  21. var p4 = document.getElementById('p4');
  22. var div1 = document.getElementById('div1');
  23. div1.appendChild(p4);
  24. console.log(p4.parentElement);
  25. console.log(div1.parentElement);
  26. console.log(div1.childNodes);
  27. console.log(div1.childNodes[0].nodeType); //text 3
  28. console.log(div1.childNodes[1].nodeType); //p 1
  29. </script>
  30. </body>
  31. </html>

#