There are two common methods in the DOM:
- append
- appendChild
Do you know the difference? Look at TypeScript types first:
append(... nodes: (Node |string) []) :void;
appendChild<T extends Node>(node: T): T;
Copy the code
See the difference? Here is a detailed interpretation:
Different parameter types
Append can insert Node or string, but appendChild can insert Node only, for example:
-
Insert node object
const parent = document.createElement('div') const child = document.createElement('p') parent.append(child) // <div><p></p></div> parent.appendChild(child) // <div><p></p></div> Copy the code
-
Insert string
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' Copy the code
Different number of parameters
Append can pass in multiple arguments but appendChild accepts only one
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>
Copy the code
Different return values
Append returns no value, but appendChild returns the inserted node object:
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>
Copy the code