What is the difference between html() and append() in jQuery?
15
I'm working with jQuery and I'm confused about when to use `$("#id").html()` versus `$("#id").append()`.
Can someone explain the key differences between these two methods and provide examples of when to use each one?
1 Answer
22
The key differences between `html()` and `append()` in jQuery are:
### html() Method
- **Replaces** all existing content inside the selected element
- Sets the innerHTML of the element
- Overwrites any existing HTML content
### append() Method
- **Adds** content to the end of the existing content
- Preserves existing content and appends new content after it
- Does not remove existing HTML content
### Examples
```javascript
// Initial HTML:
Hello
// Using html() - replaces content
$("#container").html("World");
// Result: World
// Using append() - adds content
$("#container").append(" World");
// Result: Hello World
```
### When to Use Each
- Use `html()` when you want to completely replace content
- Use `append()` when you want to add content while preserving existing content