before() and after() method in jQuery

I think you have already used before and after pseudo-elements within your CSS many times. It inserts CSS on your targeted element before or after.

Within jQuery, there are two methods with the similar name. But they position or add the element before and after instead of changing CSS.

before() and after() method in jQuery


Contents

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

1. before() method

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

Syntax –

$(selector).before( content );

Example 

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

Output

Changing position

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

Example 

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

<h1>Heading</h1>
<p>Paragraph</p>

Output


2. after() method

The method is used to insert or positioning the element after the selected element.

Syntax –

$(selector).after( content );

Example 

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

Output

Changing position

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

Example 

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

<p>Paragraph</p>
<h1>Heading</h1>

Output


3. Conclusion

You can 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.

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *