append 和 appendChild 的区别

3,179 阅读1分钟

DOM 中有两个常用的方法:

  • append
  • appendChild

你知道它们的区别吗?先看 TypeScript 类型:

append(...nodes: (Node | string)[]): void;
appendChild<T extends Node>(node: T): T;

可以看出区别了吧?下面进行详细解读:

参数类型不同

append 可插入Node节点或字符串,但 appendChild 只能插入Node节点,例如:

  • 插入节点对象

    const parent = document.createElement('div')
    const child = document.createElement('p')
    parent.append(child) // <div><p></p></div>
    parent.appendChild(child) // <div><p></p></div>
    
  • 插入字符串

    const parent = document.createElement('div')
    parent.append('text') // <div>text</div>
    parent.appendChild('text') // Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'
    

参数个数不同

append 可传入多个参数但 appendChild 只接受一个参数

const parent = document.createElement('div')
const child = document.createElement('p')
const childTwo = document.createElement('p')
parent.append(child, childTwo, 'Hello world') // <div><p></p><p></p>Hello world</div>
parent.appendChild(child, childTwo, 'Hello world') // <div><p></p></div>

返回值不同

append 没有返回值,但 appendChild 返回插入的节点对象:

const parent = document.createElement('div')
const child = document.createElement('p')
const appendValue = parent.append(child)
console.log(appendValue) // undefined
const appendChildValue = parent.appendChild(child)
console.log(appendChildValue) // <p><p>