WIT LAB INC Blog

“ To Impress Others By Works"

How to use .append, .prepend, .appendTo and .prependTo in JQuery ?

How to use .append, .prepend, .appendTo and .prependTo in JQuery ?

Good Day to you all !

If you are working with jQuery and need to dynamically update content, understanding how to use .append(), .prepend(), .appendTo(), and .prependTo() will make your work smoother and more efficient.

These methods are simple yet powerful for injecting HTML elements or text into the DOM. Below is a clear and practical explanation based on real usage scenarios.

  1. .append()

Adds content inside the selected element, after existing content.

$('#container').append('<p>New content at the bottom</p>');

Result:

<div id="container">
    Existing content
    <p>New content at the bottom</p>
</div>

2. .prepend()

Adds content inside the selected element, before existing content.

$('#container').prepend('<p>New content at the top</p>');

Result:

<div id="container">
    <p>New content at the top</p>
    Existing content
</div>

3. .appendTo()

Same effect as .append(), but the syntax is reversed.

$('<p>Added using appendTo</p>').appendTo('#container');

Result:

$('#container').append('<p>Added using appendTo</p>');

4. .prependTo()

Same as .prepend(), with reversed syntax.

$('<p>Added using prependTo</p>').prependTo('#container');

Result:

$('#container').prepend('<p>Added using prependTo</p>');

Usage Tips

  1. Use .append() or .prepend() if you already have the container ID or class.
  2. Use .appendTo() or .prependTo() when creating elements dynamically or reusing the element.
  3. Don’t forget to sanitize content if using user input.
  4. Chainable methods help reduce code repetition.

Add multiple list items using Chain Method

$('<li>New Item</li>')
    .appendTo('#myList')
    .clone().appendTo('#myList')
    .clone().appendTo('#myList');

Hope this helps you better understand and apply these jQuery methods in real projects!

Page Top