<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>DOM增删改查</title>
</head>
<body>
<section id="SEC1"></section>
<script type="text/javascript">
// 通过元素id来查找元素
const sec1 = document.getElementById(‘SEC1‘)
// 创建一个元素
const span = document.createElement(‘span‘)
span.className = ‘class-span‘
let spanText = document.createTextNode(‘this is span‘)
span.appendChild(spanText)
// 将span添加到sec1中
sec1.appendChild(span)
// 替换元素
const div1 = document.createElement(‘div‘)
div1.id = ‘ID_Div1‘
div1.className = ‘class-div1‘
div1.innerHTML = ‘this is div1‘
sec1.replaceChild(div1, span)
// 循环插入元素
// 创建一个文档片段,此时还没有插入到DOM树中
const div2 = document.createElement(‘div‘)
div2.id = ‘ID_Div2‘
div2.className = ‘class-div2‘
sec1.appendChild(div2)
const frag = document.createDocumentFragment()
for (let i = 1; i <= 6; i++) {
let p = document.createElement(‘p‘)
p.className = ‘class-p‘
p.innerHTML = `this is p${i}`
frag.appendChild(p)
}
// 都完成后,再插入到 DOM 树中
div2.appendChild(frag)
// 删除元素
const pList = document.getElementsByClassName(‘class-p‘)
div2.removeChild(pList[pList.length - 1])
</script>
</body>
</html>