jQuery before() and after()

The jQuery before() and after() methods are used to insert content adjacent to selected elements within the DOM.

jQuery before()

The before() method inserts content before the selected elements. It can accept various input types like HTML strings, DOM elements, or jQuery objects. This method is useful when you want to add content immediately preceding the selected elements.

$("h2").before("<p>New paragraph added</p>");
<h2>jQuery before()</h2>
run this source code Browser View

jQuery before()

In the above example will insert a paragraph before the container element h2 .

Full Source
<html> <head> <title>jQuery before method example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#btn").click(function(){ $("h2").before("<p>New paragraph added</p>"); }); }); </script> </head> <body> <button id="btn">Before</button> <h2>jQuery before()</h2> </body> </html>

jQuery after()

The after() method inserts content after the selected elements. It follows the same pattern of accepting various types of input and is applied when you want to add content immediately following the selected elements.

$("h2").after("<p>New paragraph added</p>");
<h2>jQuery after()</h2>

In the above example will insert a paragraph after the container element h2 .

run this source code Browser View

jQuery before()

Full Source
<html> <head> <title>jQuery after() method example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#btn").click(function(){ $("h2").after("<p>New paragraph added</p>"); }); }); </script> </head> <body> <button id="btn">After</button> <h2>jQuery before()</h2> </body> </html>

Conclusion

Both methods are commonly employed to dynamically modify the arrangement and appearance of web page elements, enabling developers to insert or append content without requiring manual restructuring of the HTML structure.