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()
- The prepend() method inserts content as the first child of the selected element.
- It creates a new element or elements and places them at the beginning of the selected element.
- If multiple elements are selected, prepend() will be applied to each of them individually.
$('#myList').prepend('<li>New Item</li>');
append()
- The append() method inserts content as the last child of the selected element(s) in the DOM.
- 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()
- The before() method inserts content immediately before the selected element(s).
- It creates a new element or elements and places them directly before the selected element.
- 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()
- The after() method inserts content after the selected element(s) in the DOM.
- 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.
Related Topics