To add elements using jQuery, you can use several methods depending on your specific needs. Here are some examples:
- .append() – Adds new content to the end of the selected element(s).
$('#myList').append('<li>New item</li>');
This will add a new list item with the text “New item” to the end of the unordered list with the ID “myList”.
- .prepend() – Adds new content to the beginning of the selected element(s).
$('#myList').prepend('<li>New item</li>');
This will add a new list item with the text “New item” to the beginning of the unordered list with the ID “myList”.
- .after() – Inserts new content after the selected element(s).
$('#myList li:last').after('<li>New item</li>');
This will add a new list item with the text “New item” after the last list item in the unordered list with the ID “myList”.
- .before() – Inserts new content before the selected element(s).
$('#myList li: first').before('<li>New item</li>');
This will add a new list item with the text “New item” before the first list item in the unordered list with the ID “myList”.
- .html() – Replaces the content of the selected element(s) with new content.
$('#myDiv').html('<p>New content</p>');
This will replace the existing content of the div with the ID “myDiv” with a new paragraph containing the text “New content”.
- .text() – Replaces the text content of the selected element(s) with new text.
$('#mySpan').text('New text');
This will replace the existing text content of the span with the ID “mySpan” with the new text “New text”.
