jQuery - Insert Elements

It is simple to add fresh elements/content to jQuery.

Create an Entirely new HTML Document

We'll take a glance at 4 different jQuery methods for introducing new subject matter:

append() - Plugs content just at finish of the elements that have been chosen.

prepend() - Adds content to a starting of the sample elements.

after() - Plugs content well after elements that have been chosen.

before() - Gets added content before even the stipulated elements.


append() method through jQuery

The jQuery append() method adds content to the finish of the HTML elements you've chosen.

Illustration:

EXAMPLE ❯


prepend() method in jQuery

The prepend() method of the jQuery library inserts content at the start of the chosen Html pages.

Illustration:

EXAMPLE ❯


Use append() and prepend() to add numerous different additions ()

In each of the preceding illustrations, we purely embedded several text/HTML at the start and the end of the picked HTML elements.

The append() and prepend() methods, on the other hand, could indeed take an endless range of new elements as parameters. The new features can be created using text/HTML (as in the examples above), jQuery, or Javascript and DOM elements.

In the illustration below, we add several new elements. Text/HTML, jQuery, and JavaScript/DOM were used to create the elements. The new elements are then appended to the text using the append() method (it could also collaborate for prepend() ):

Illustration:

EXAMPLE ❯


jQuery after() and before() Methods

The jQuery after() method inserts content AFTER the selected HTML elements.

The jQuery before() method inserts content BEFORE the selected HTML elements.

EXAMPLE ❯


Add Several New Elements With after() and before()

Also, both the after() and before() methods can take an infinite number of new elements as parameters. The new elements can be generated with text/HTML (like we have done in the example above), with jQuery, or with JavaScript code and DOM elements.

In the following example, we create several new elements. The elements are created with text/HTML, jQuery, and JavaScript/DOM. Then we insert the new elements to the text with the after() method (this would have worked for before() too) :

Example:

function afterText() {

  var txt1 = "<b>I </b>";                    // Create element with HTML 

  var txt2 = $("<i></i>").text("love ");     // Create with jQuery

  var txt3 = document.createElement("b");    // Create with DOM

  txt3.innerHTML = "jQuery!";

  $("img").after(txt1, txt2, txt3);          // Insert new elements after <img>

}