How to Use before() and after() method in jQuery

In CSS before and after pseudo-elements use to add style to the targeted selector elements.

There are two methods with a similar name in jQuery.

They adjust the position or add the element before and after instead of changing CSS.

In this tutorial, with examples, I show how you can use before() and after() methods on your webpage.

How to Use before() and after() method in jQuery


Contents

  1. before() method
  2. after() method
  3. Conclusion

1. before() method

This method is use to insert or positioning the element before the selected element.

Syntax –

$(selector).before( content );

Example 

<script type='text/javascript'>
$(document).ready(function(){
    $("h2").before( "<b>Text added before h2</b>" );
});
</script>
<h2>Heading</h2>

View Demo


Changing position

Adjust the position of an element with before() method.

Example 

<script type='text/javascript'>
 $(document).ready(function(){
   $("h2").before( $("p") );
 });
</script>

<h2>Heading</h2>
<p>Paragraph</p>

View Demo


2. after() method

This method is used to insert or position the element after the selected element.

Syntax –

$(selector).after( content );

Example 

<script type='text/javascript'>
$(document).ready(function(){
    $("h2").after( "<b>Text added after h2 </b>" );
});
</script>
<h2>Heading</h2>

View Demo


Change position

Adjusting the position of an element with the after() method.

Example 

<script type='text/javascript'>
 $(document).ready(function(){
      $("h2").after( $("p") );
 });
</script>

<p>Paragraph</p>
<h2>Heading</h2>

View Demo


3. Conclusion

Use this method to adjust the position of the element or add new content.

If you want to insert content but don’t want to do any manipulation related to before or after then you can use .append() or .html() methods.

If you found this tutorial helpful then don't forget to share.

Leave a Comment