Blogger Information
Blog 18
fans 0
comment 2
visits 10459
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
dom元素的增删改操作
go0
Original
618 people have browsed it

dom元素的增删改操作

增加

  1. <script>
  2. const ul = document.createElement("ul");
  3. document.body.append(ul);
  4. for (let i = 0; i < 5; i++) {
  5. const li = document.createElement("li");
  6. li.textContent = "item" + (i + 1);
  7. ul.append(li);
  8. }
  9. console.log(ul);
  10. console.log(ul.outerHTML);
  11. </script>

关键的操作都在上面的代码中,很直观。最后的两句输出的结果如下所示:

outerHTML是元素的html字符串表示

插入

  1. const three = document.querySelector("ul li:nth-of-type(3)");
  2. const li = document.createElement("li");
  3. li.textContent = "new item";
  4. li.style.color = "red";
  5. three.before(li);
  6. let cloneli = li.cloneNode(true);
  7. three.after(cloneli);

函数名称都说明了函数的功能。注意一点,cloneNode如果没有参数true,就不是深克隆,那么节点的文本内容等属性就不能复制过去。


  1. const h3 = document.createElement("h3");
  2. h3.textContent = "商品列表";
  3. ul.insertAdjacentElement("beforeBegin", h3);


还有afterBegin,beforeEnd,afterEnd.

替换

  1. const last = document.querySelector("ul li:last-of-type");
  2. const a = document.createElement("a");
  3. a.href = "https://php.cn";
  4. a.textContent = "php.cn";
  5. ul.replaceChild(a, last);

移除

  1. ul.lastElementChild.remove();

textContent

  1. <body>
  2. <div class="box">
  3. <style>
  4. h2 {
  5. color: red;
  6. }
  7. </style>
  8. <h2>通知</h2>
  9. <span style="display: none">13:00--14:00会供电</span>
  10. <p>本小区明天8:00-18:00停电</p>
  11. </div>
  12. <script>
  13. const box = document.querySelector(".box");
  14. console.log(box.textContent);
  15. </script>
  16. </body>


拿到的是内部所有标签的文本内容,不显示(display:none)的也能拿到
和它类比,还有一个很很很常用的是innerText.

  1. console.log(box.innerText);


一对比就能看出来,哪些style,display:none等它不拿。
还有一个innerHTML,是最好理解的,内部所有的HTML都取出来。看例子

  1. console.log(box.innerHTML);

innerText在2016年才成为W3C的标准,textContent兼容更好一些。

innerText 和 innerHTML

  1. let p = document.createElement("p");
  2. let url = '<a href="https://php.cn"> php.cn </a>';
  3. p.innerText = url;
  4. box.append(p);

  1. let p = document.createElement("p");
  2. let url = '<a href="https://php.cn"> php.cn </a>';
  3. p.innerHTML = url;
  4. box.append(p);

outerHTML

这个是返回当前自身的HTML字符串

  1. console.log(box.outerHTML);
  2. box.outerHTML = null; // 清空,当然也可以替换成其他内容,用null清空。

Correcting teacher:PHPzPHPz

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