Adding and Removing JQuery Html Element

We can add new HTML elements and content to the web page with JQuery. Let's talk about 4 methods we can use for this purpose:

prepend() – Adds content to the head of the specified HTML element.

append() – Allows content to be added to the last part of the specified HTML element.

before() - Allows content to be added before the specified html element.

after() - Allows content to be added after the specified html element.

For example, let's add a new paragraph to the top of the page:


$("body").prepend("<‍p><‍b>Paragraph added.<‍/b><‍/p>");

// We can add it to the end of the page with the append method instead of prepend:

$("body").append("<‍p><‍b>Paragraph added.<‍/b><‍/p>");

// Be - add a new line to the end of the sorted list:

$("#mylist").append("<‍li><‍b>Row added.<‍/b><‍/li>");

// Let's add a paragraph before a div element:

$("#box1").before("<‍u>Before box1<‍/u>");

Removing JQuery Html Element

With jQuery, we can add new elements to the web page as well as remove elements from the page. The remove method is used to completely remove a tag with all its content, and the empty method is used to remove only the content of the tag.

For example, let's completely remove the div element named box1:


$("#box1").remove();

Let's remove only the contents of Box1:

$("#box1").empty();

If desired, you can specify which of the same tags will be removed by using a parameter in the Remove method. Example: Let's say the "warning" class is applied to some p tags on our page. We can remove these p tags as follows:

$("p").remove(".warning");