
How to add an element after another element using jQuery
In this article, we will explain to you how to add an element after another element using jquery. so we will give you a simple example of how to add an element after another element using jquery.
Example: jQuery insertAfter() method
In this example, we use jQuery insertAfter() method to add an element after the specific element. so you can follow the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("<span>red</span>").insertAfter("p"); }); }); </script> </head> <body> <button>add span element after the p element</button> <p>Color:- </p> </body> </html> |
Example: jQuery after() method
In this example, we use jQuery after() method to add an element after the specific element. so you can follow the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").after("<span>red</span>"); }); }); </script> </head> <body> <button>add span element after the p element</button><br/> <p>Color:- </p> </body> </html> |