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

Asked 3 years ago 182 views 1 answer Modified 19 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?

CodingerWeb
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

// Initial HTML: <div id="container">Hello</div>

// Using html() - replaces content
$("#container").html("World");
// Result: <div id="container">World</div>

// Using append() - adds content
$("#container").append(" World");
// Result: <div id="container">Hello World</div>

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: 1 months ago
Preview: