Inserting HTML with jQuery

This YouTube video was created by Steve Griffith.

One of the core reasons for the JavaScript's existence, was the creation and insertion of new HTML elements. Now, how elements are inserted in the HTML generally depends on where they need to be inserted. But, there typically four locations: before the target element, after the target element, the first child of the target element, or the last child of the target element.

The jQuery library provides these exact same option for use using the before()open in new window, after()open in new window, prepend()open in new window, append()open in new window methods.

NOTE

All of methods above, the target element precedes the method, which is the followed by the content or the new element. The jQuery library also has methods in which the content precedes the method. They are insertBefore()open in new window, insertAfter()open in new window, prependTo()open in new window, appendTo()open in new window.

Assume the following HTML element with the four locations marked with one (before element), two (first child), three (last child), four (after element).

<!-- one -->
<p class="original">
  <!-- two -->
  This is the original paragraph.
  <!-- three -->
</p>
<!-- four -->

Now, the jQuery can be used to insert new element in HTML at each of the four locations.

// Before Element
$('.original').before('<p>One</p>')

// After Element
$('.original').after('<p>Four</p>')

// First Child
$('.original').prepend('<span>Two</span>')

// Last Child
$('.original').append('<span>Three</span>')