新增节点

代码格式

先创建一个节点,后放入指定元素

创建节点
1
2
3
4
5
6
<script>
const div = document.createElement('div')
div.innerHTML = '豆棍杜子'
div.style.fontSize = '20px'
console.log(div)
</script>

放入指定元素,appendChild()方法
1
2
3
4
5
6
7
8
9
10
<span>
</span>
<script>
const div = document.createElement('div')
div.innerHTML = '豆棍杜子'
div.style.fontSize = '20px'
console.log(div)
const span = document.querySelector('span')
span.appendChild(div)
</script>

放在某个指定元素前面,insertBefore()方法
1
2
3
4
const h1 = document.createElement('h1')
h1.innerHTML = 'Good morning!'
h1.style.backgroundColor = "blue"
span.insertBefore(h1,div)