jQuery Insert Elements Before and After

jQuery Insert Elements Before and After Certain Elements

In this article, I am going to discuss How to Insert Elements Before and After Certain Elements in jQuery with Examples. Please read our previous article, where we discussed jQuery Append and Prepend Elements. At the end of this article, you will understand everything about how to insert elements before and after elements.

jQuery Insert Elements Before and After Certain Elements

If you have to insert a specified content before any selected element(s), then jQuery provides you a built-in method before(). Similarly, if you have to insert a specified content after any selected element(s), then jQuery has a method after(). This sounds similar to append() & prepend() which we have learned in the previous article. But there is a huge difference.

append() vs .after()
  1. .append(): Insert content, specified by the parameter, to the end of each element in the set of matched elements.
  2. .after(): Insert content, specified by the parameter, after each element in the set of matched elements.
prepend() vs .before()
  1. prepend(): Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
  2. .before(): Insert content, specified by the parameter, before each element in the set of matched elements.

So, append and prepend refers to the child of the object whereas after and before refers to the sibling of the object.

jQuery before() Method

Syntax: $(selector).before(content, function(index))
Parameters:
Content: This is a required parameter. This specifies the content to insert (can contain HTML tags)
Function: This is an optional callback function. It takes an optional parameter

  1. index – Returns the index position of the element in the set
Example: jQuery before() Method

In the below example, we have a div and inside that some content. By before() method, we are inserting a <h2> element before the <div> element.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Before and After</title>
</head>
<body>
    <h3>jQuery Before and After</h3>
    <section>
      <div class="div1">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
    </section>
    </br>
    <button class="demo before">Before</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".before").click(function () {
          $("div").before("<h2>This is title of the div</h2>");
        });
      });
    </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and have a look at the Elements tab as shown in the below image.

jQuery Insert Elements Before and After with Examples

Now, click on the Before button and have a look at the elements tab as well as browser, you will see that h2 element is added before the div element as shown in the below image.

jQuery Insert Elements Before and After with Examples

Example: jQuery Before Method

We can also insert an existing element of the DOM before any specified element. If the content is an existing element, it will be moved from its current position, and inserted before the selected elements.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Before and After</title>
</head>
<body>
    <h3>jQuery Before and After</h3>
    <section>
      <div class="div1">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
    </section>
    <h2>This is title of the div</h2>
    </br>
    <button class="demo before">Before</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".before").click(function () {
          $("div").before($("h2"));
        });
      });
    </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and have a look at the Elements tab as shown in the below image. Notice that the <h2> element is present in our DOM after the <section> element.

jQuery Before Method Example

Now, click on the Before button, and observe that the <h2> was inserted before <div> element. Notice that inside the before() method we have used a jQuery selector as a parameter.

jQuery Before Method Example

Example: jQuery Before Method Using the callback function

In the below example, we have two <div> elements present in our DOM. before() method is iterating implicitly over them and performing a function. Parameter index is receiving the current index no. of the <div>. The new content is inserted before each of the div.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Before and After</title>
</head>
<body>
    <h3>jQuery Before and After</h3>

    <section>
      <div class="div1">
        Lorem ipsum dolor sit amet consectetur adipisicing elit.
      </div>
      <div class="div2">
        Maiores porro quibusdam deserunt id unde odit fugit libero.
      </div>
    </section>
    </br>
    <button class="demo before">Before</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".before").click(function () {
          $("div").before(function (index) {
            return `<h2>This is the title of div indexed at ${index}:</h2>`;
          });
        });
      });
    </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and have a look at the Elements tab as shown in the below image.

jQuery Before Method Using the callback function

Now, click on the Before button, and observe that the <h2> was inserted before each <div> element as shown in the below image.

jQuery Before Method Using the callback function

jQuery insertBefore() Method

The .before() and .insertBefore() methods perform the same task. The major difference is in the syntax specifically, in the placement of the content and target. With .before(), the content to be inserted comes from the method’s argument: $(target).before(contentToBeInserted). With .insertBefore(), on the other hand, the content precedes the method and is inserted before the target, which in turn is passed as the .insertBefore() method’s argument: $(contentToBeInserted).insertBefore(target)

(Reference: https://api.jquery.com/after/)

Syntax: $(content).insertBefore(selector)

Example: jQuery insertBefore() Method

In the below example, we are inserting a <h2> element before only that <div> having class ‘div2’

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Before and After</title>
</head>
<body>
    <h3>jQuery InsertBefore Method</h3>
    <section>
      <div class="div1">
        Lorem ipsum dolor sit amet consectetur adipisicing elit.
      </div>
      <div class="div2">
        Maiores porro quibusdam deserunt id unde odit fugit libero.
      </div>
    </section>
    </br>
    <button class="demo before">Before</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".before").click(function () {
          $("<h2>This is a title</h2>").insertBefore("div.div2");
        });
      });
    </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and have a look at the Elements tab as shown in the below image. Here, you can see, we have two div elements. The first div element is having class div1 and the second div element is having class div2.

jQuery insertBefore() Method

Now, click on the Before button, and observe that the <h2> was inserted before the <div> element having class div2 as shown in the below image.

jQuery insertBefore() Method with Examples

jQuery after() method

Syntax: $(selector).after(content,function(index))
Parameters:
Content: This is a required parameter. This specifies the content to insert (can contain HTML tags)
Function: This is an optional callback function. It takes an optional parameter.

  1. index – Returns the index position of the element in the set
Example: jQuery after() method

In the below example, we have a div and inside that some content. By after() method, we are inserting a <h2> element after the <div>

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Before and After</title>
</head>
<body>
    <h3>jQuery Before & After</h3>
    <section>
      <div class="div1">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
    </section>
    </br>
    <button class="demo after">After</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".after").click(function () {
          $("div").after("<h2>This is a Title</h2>");
        });
      });
    </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and have a look at the Elements tab as shown in the below image.

jQuery after() method

Now, click on the After button, and observe that the <h2> was inserted after the <div> element as shown in the below image.

jQuery after() method with Examples

Note: We can use the callback exactly the same as the before() method. This is a task for you. Please do the same task and give your code in the comment section.

jQuery insertAfter() method

The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With .after(), the content to be inserted comes from the method’s argument: $(target).after(contentToBeInserted). With .insertAfter(), on the other hand, the content precedes the method and is inserted after the target, which in turn is passed as the .insertAfter() method’s argument: $(contentToBeInserted).insertAfter(target).

(Reference: https://api.jquery.com/after/)

Syntax: $(content).insertAfter(selector)

Example: jQuery insertAfter() method

In the below example, we are using insertAfter() to insert content after each of the selected <div>

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Before and After</title>
</head>
<body>
    <h1>jQuery Insert After</h1>
    <section>
      <div class="div1">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div class="div2">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
    </section>
    </br>
    <button class="demo after">After</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".after").click(function () {
          $("<h2>This is a Title</h2>").insertAfter("div");
        });
      });
    </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and have a look at the Elements tab as shown in the below image.

how to insert elements before and after certain elements in jQuery with Examples

Now, click on the After button, and observe that the <h2> was inserted after each <div> element as shown in the below image.

how to insert elements before and after certain elements in jQuery with Examples

To insert an element before another element

  1. Before
  2. insertBefore

To insert an element after another element

  1. after
  2. inserAfter

As these methods modify DOM, they belong to the DOM manipulation category.

In the next article, I am going to discuss How to add or remove class using jQuery with Examples. Here, in this article, I try to explain how to insert elements before and after certain elements in jQuery with Examples and I hope you enjoy this jQuery Insert Elements Before and After article.

Leave a Reply

Your email address will not be published.