A common code task is inserting elements in the DOM. For example, if the data returned by an Ajax call contains DOM elements, then your JavaScript handler will need to insert those elements somewhere on the page. How you go about this depends on whether you have jQuery loaded. In this tutorial, I’ll give you a quick look at some of the DOM insertion methods that jQuery offers, then I’ll show you their vanilla JavaScript equivalents.
If you’re using jQuery in your project, you get a fistful of ways to insert elements, but the following four are the most common:
-
target.before(content)
: Inserts the element(s) specified by thecontent
selector as adjacent siblings before each element specified by thetarget
selector. (Learn more.) Here’s an example: -
target.after(content)
: Inserts the element(s) specified by thecontent
selector as adjacent siblings after each element specified by thetarget
selector. (Learn more.) Here’s an example: -
target.prepend(content)
: Inserts the element(s) specified by thecontent
selector as children at the beginning of the element specified by thetarget
selector. (Learn more.) Here’s an example: -
target.append(content)
: Inserts the element(s) specified by thecontent
selector as children at the end of the element specified by thetarget
selector. (Learn more.) Here’s an example:
$('#target').before($('<h2>Hello DOM Insertion World!</h2>'))
$('#target').after($('<h2>Hello DOM Insertion World!</h2>'))
$('#target').prepend($('<h2>Hello DOM Insertion World!</h2>'))
$('#target').append($('<h2>Hello DOM Insertion World!</h2>'))
For smaller projects, jQuery might be overkill. Fortunately, you don’t need jQuery to perform the same DOM insertion tasks using vanilla JS. Even better, the equivalent JS methods are almost easier done than said, as the following sections show.
To perform the equivalent of jQuery’s .before
method — that is, to insert an element as an adjacent sibling that appears before a target element — use the insertAdjacentHTML
method with the position
parameter set to beforebegin
:
target.insertAdjacentHTML('beforebegin', content)
To perform the equivalent of jQuery’s .after
method — that is, to insert an element as an adjacent sibling that appears after a target element — use the insertAdjacentHTML
method with the position
parameter set to afterend
:
target.insertAdjacentHTML('afterend', content)
To perform the equivalent of jQuery’s .prepend
method — that is, to insert an element as a child that appears at the beginning of a target element — use the insertAdjacentHTML
method with the position
parameter set to afterbegin
:
target.insertAdjacentHTML('afterbegin', content)
To perform the equivalent of jQuery’s .append
method — that is, to insert an element as a child that appears at the end of a target element — use the insertAdjacentHTML
method with the position
parameter set to beforeend
:
target.insertAdjacentHTML('beforeend', content)