What is the difference between html() and append() in jQuery?

Asked 3 years ago 253 views 1 answer Modified 6 hours ago
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?
imran-nadwi
175 reputation

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
abdul-qadir
answered 3 years ago
You can use Markdown to format your answer.
Last edited: 5 months ago
Preview: