- 创建dom元素 div, span
- 附加span到div列表中
用cloneNode(true)复制span到div中,以完整保留元素内部结构
<scrypt>
let div = document.createElement(“div”);
let span = document.createElement(“span”);
span.textContent = “Hello”;
div.append(span);
div.append(span, “ world”);
document.body.append(span.cloneNode(true), “ world”);
</scrypt>添加ul items到body里面
const ul = document.createElement(“ul”);
for(let i = 1, i <= 5; i++) {
let li = document.createElement(“li”);
li.textContent =item${i}
;
li.style.color = “red”;
ul.append(li);
document.body.append(ul);
}前置一个item-prepend
li = document.createElement(“li”);
li.textContent = “first item”;
li.style.color = blue;
ul.prepend(li);中间位置添加,querySelector节点前后
const referNode = document.querySelector(“li:nth-of-type(4)”);
referNode.style.background = “lightblue”;
li = document.createElement(“li”);
li.textContent = “new content before”;
li.style.background = “yellow”;
referNode.before(li);
后:
li = document.createElement(“li”);
li.textContent = “new content after”;
li.style.background = “purple”;
referNode.after(li);链接替换最后那个节点
let lastItem = document.querySelector(“ul li:last-of-type”);
let a = document.createElement(“a”);
a.textContent = “google”;
a.href = “http://www.google.com“;
lastItem.replaceWith(a);删除节点
ul.querySelector(“:nth-of-type(6)”).remove();插入4个邻近的元素insertAdjacentElement
- beforeBegin
- afterBefin
- beforeEnd
afterEnd
li = document.createElement(“li”);
li.textContent = “the first child element”;
ul.insertAdjacentElement(“afterbegin”, li); ul.insertAdjacentElement(“beforebegin”, li);在结尾添加,用HTML
ul.insertAdjacentHTML(“beforeEnd”, ‘<li style="color:red">the last child element</li>‘ );- 直接插入文本
const h2 = document.createElement(“h2”);
h2.insertAdjacentText(“beforeend”, ul.lastElementChild.textContent);
console.log(h2);
document.body.insertAdjacentElement(“afterend”, h2);