Adding and removing content in jQuery

javascriptjquery

jQuery provides several methods for adding and removing content from an HTML document.

Here are some examples of how you can use these methods:

To add new content to the end of an element:

$('#my-element').append('<p>New content</p>');

To add new content to the beginning of an element:

$('#my-element').prepend('<p>New content</p>');

To replace the content of an element:

$('#my-element').html('<p>New content</p>');

To remove an element:

$('#my-element').remove();

To remove the content of an element:

$('#my-element').empty();

Keep in mind that these methods can accept not only string arguments, but also jQuery objects and DOM elements, allowing you to add or remove complex structures of content.

For example, you can use the append() method to add a new element to the page like this:

const newElement = $('<p>New content</p>');
$('#my-element').append(newElement);

Or you can use the remove() method to remove an element from the page like this:

const elementToRemove = document.getElementById('my-element');
$(elementToRemove).remove();