Blogger Information
Blog 16
fans 0
comment 0
visits 9511
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
dom树元素的增删改查
Blastix Riotz
Original
625 people have browsed it
  1. <script>
  2. //创建dom元素
  3. let div = document.createElement("div");
  4. let span = document.createElement("span");
  5. // console.log(div,span);
  6. span.textContent = "hello";
  7. // append(lel,'text'),将参数作为父元素的最后一个子元素追加到列表中,无返回值
  8. // span 添加到div中
  9. div.append(span);
  10. div.append(span,"world");
  11. console.log(div);
  12. // document.body.append(div);
  13. // document.body.append(span,"world");
  14. //为什么div中的span消失了?
  15. //新元素span只能插入到一个地方
  16. //span在 div,现在span在body中,相当于剪切操作
  17. //如果想保留span在div中,需要克隆span
  18. // true:是完整的保留元素内部结构
  19. document.body.append(span.cloneNode(true),"world");
  20. // append()创建一个列表
  21. const ul = document.createElement("ul");
  22. //循环生成列表项li
  23. for (let i = 1;i <= 5 ; i++){
  24. let li = document.createElement("li");
  25. li.textContent = `item${i}`;
  26. // li.style.color = "red";
  27. ul.append(li);
  28. }
  29. document.body.append(ul);
  30. //和append()尾部追加,对应的;prepend() 在头部追加
  31. li = document.createElement("li");
  32. li.textContent = 'first item';
  33. li.style.color = "red";
  34. ul.prepend(li);
  35. //如果是在除了头部和尾部之外的地方添加
  36. //必需要有一个参考节点
  37. //以第四个节点为参考
  38. const referNode = document.querySelector("li:nth-of-type(4)");
  39. referNode.style.background = "cyan";
  40. //在它之前添加一个新节点
  41. li = document.createElement("li");
  42. li.textContent = "在参考节点之前插入";
  43. li.style.background = "yellow";
  44. //referNode.before(el),在插入节点上调用
  45. referNode.before(li);
  46. li = document.createElement("li");
  47. li.textContent = "在参考节点之后插入";
  48. li.style.background = "violet";
  49. //referNode.after(el),在插入节点上调用
  50. referNode.after(li);
  51. //替换节点
  52. //将最后一个节点用链接替换
  53. let lastItem = document.querySelector("ul li:last-of-type");
  54. let a = document.createElement("a");
  55. a.textContent = "替换网址";
  56. a.href = "https://baidu.com";
  57. lastItem.replaceWith(a);
  58. //删除节点,在被删除的节点上直接调用 remove(无参数)
  59. ul.querySelector(':nth-of-type(6)').remove();
  60. </script>
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post