JQuery  Add Elements

To add elements using jQuery, you can use several methods depending on your specific needs. Here are some examples:

  1. .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”.

  1. .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”.

  1. .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”.

  1. .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”.

  1. .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”.

  1. .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”.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *