Skip to content
html
<!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>Document</title>
</head>
<body>
  <!--
    createElement:创建元素对象
    createTextNode:创建文本节点
    appendChild:容器.appendChild(元素) 把元素添加到容器内部的末尾
    insertBefore:容器.insertBefore(新增元素, 指定元素) 把元素添加到指定容器的前面
    replaceChild: oldEle.parentNode.replaceChild(newEle, oldEle) 新元素替换老元素
    removeChild: parent.removeChild(child)
   -->

  <h3 id="foo">foo</h3>
  
  <script>
    // 创建元素对象
    const box = document.createElement('div')
    box.id = 'box01'
    box.className = 'box02'
    box.style.width = '200px'
    box.style.cssText = `
      height: 200px;
      background: pink;
    `

    // 创建文本节点
    const text = document.createTextNode('我是文本节点')
    const foo = document.querySelector('#foo')

    // 添加到末尾
    box.appendChild(text)

    // 添加到指定容器前面
    foo.parentNode.insertBefore(box, foo)
    // document.body.insertBefore(box, foo) // 等效于上面
  </script>
</body>
</html>