jquery append() and prepend()

The jQuery append() and prepend() methods are used to manipulate the content of selected elements by inserting new elements or text within them.

jQuery append() method

The append() method adds content at the end of the selected elements. It can accept various types of input, such as HTML strings, DOM elements, or jQuery objects. This method is often used to add new elements or text as the last child of the selected elements.

$("ol").append("<li>New Item</li>");
<ol> <li>Itel 1</li> <li>Item 2</li> <li>Item 3</li> </ol>

The above code will append an item to the list, meaning that the new item will be inserted as the last item.

run this source code Browser View
  1. Item 1
  2. Item 2
  3. Item 3
Full Source
<html> <head> <title>jQuery append() methos example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#btn").click(function(){ $("ol").append("<li>New Item</li>"); }); }); </script> </head> <body> <button id="btn">Append Item</button> <ol> <li>Itel 1</li> <li>Item 2</li> <li>Item 3</li> </ol> </body> </html>

jQuery prepend()

The prepend() method inserts content at the beginning of the selected elements. Like append(), it can also take different types of input. This method is useful when you want to insert content as the first child within the selected elements.

$("ol").prepend("<li>New Item</li>");
<ol> <li>Itel 1</li> <li>Item 2</li> <li>Item 3</li> </ol>
run this source code Browser View
  1. Itel 1
  2. Item 2
  3. Item 3

The above code will prepend an item to the list, meaning that the new item will be inserted at the beginning of the list.

Full Source
<html> <head> <title>jQuery prepend() method example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#btn").click(function(){ $("ol").prepend("<li>New Item</li>"); }); }); </script> </head> <body> <button id="btn">Prepend</button> <ol> <li>Itel 1</li> <li>Item 2</li> <li>Item 3</li> </ol> </body> </html>

Conclusion

Both methods are commonly used for dynamically populating HTML structures, creating new elements on-the-fly, and enhancing user interfaces by adding or inserting content without requiring a page refresh.