jQuery :prepend(), append(), before() , after()

The jQuery methods prepend(), append(), before(), and after() are used for manipulating the content of selected elements within the Document Object Model (DOM).

prepend()

  1. The prepend() method inserts content as the first child of the selected element.
  2. It creates a new element or elements and places them at the beginning of the selected element.
  3. If multiple elements are selected, prepend() will be applied to each of them individually.
$('#myList').prepend('<li>New Item</li>');

append()

  1. The append() method inserts content as the last child of the selected element(s) in the DOM.
  2. It works similar to prepend(), but the content is added at the end of the selected element(s).
$('#container').append('<p>New Paragraph</p>');

before()

  1. The before() method inserts content immediately before the selected element(s).
  2. It creates a new element or elements and places them directly before the selected element.
  3. If multiple elements are selected, the inserted content will be placed before each of them individually.
$('<li>New Item</li>').before('#myList li:first-child');

after()

  1. The after() method inserts content after the selected element(s) in the DOM.
  2. It works similar to before(), but the content is added after the selected element(s).
$('p').after('<p>New Paragraph</p>');

Conclusion

These methods facilitate dynamic changes to a webpage's structure and appearance, allowing the addition of new elements or text without the need for manual HTML editing. By using these methods, developers can create interactive user experiences and update content on-the-fly.