What's the Difference Between append and appendChild in JavaScript?
What's the Difference Between append and appendChild in JavaScript?
The Core Difference
The main difference between append and appendChild is simple:
appendaccepts text strings AND nodes (DOM elements)appendChildonly accepts nodes (DOM elements)
Example: Using append
With append, you can add both text and elements in one call:
1
2
3
4
5
6
let div = document.createElement("div")
let p = document.createElement("p")
div.append("Some text", p)
console.log(div.childNodes)
// NodeList [ #text "Some text", <p> ]
Example: Using appendChild
With appendChild, you can only add nodes. If you want to add text, you need to create a text node first:
1
2
3
4
5
6
7
8
9
10
11
12
let div = document.createElement("div")
let p = document.createElement("p")
// This works
div.appendChild(p)
// This doesn't work - will throw an error
div.appendChild("Some text") // Error: Wrong type of argument
// To add text, create a text node
let textNode = document.createTextNode("Some text")
div.appendChild(textNode)
Browser Compatibility
Most modern browsers support append, but not obsolete browsers like Internet Explorer.
In browsers without support for append, you’ll see this error:
1
object doesn't support property or method 'append'
Comparison
| Feature | append() | appendChild() |
|---|---|---|
| Accepts strings | ✅ Yes | ❌ No |
| Accepts nodes | ✅ Yes | ✅ Yes |
| Multiple arguments | ✅ Yes | ❌ No |
| Returns value | undefined | The appended node |
| IE support | ❌ No | ✅ Yes |
| Modern browsers | ✅ Yes | ✅ Yes |
Before and After
Before (IE-compatible):
1
2
3
4
5
6
7
let div = document.createElement("div")
// Add an element
div.appendChild(document.createElement("p"))
// Add text (needs text node)
div.appendChild(document.createTextNode("Some text"))
After (modern browsers):
1
2
3
4
let div = document.createElement("div")
// Add both in one call
div.append("Some text", document.createElement("p"))
What I Learned
appendis more flexible — Being able to pass strings directly is convenient and reduces boilerplate code- Know your target browsers — If you need to support Internet Explorer, stick with
appendChild - Both methods are useful —
appendChildreturns the node you appended, which can be useful for chaining or reference.appendreturnsundefinedbut lets you add multiple items at once - Check MDN for compatibility — The browser compatibility tables on MDN are invaluable when deciding which API to use
For more information, check the MDN documentation.
This post is licensed under CC BY 4.0 by the author.