$(document).ready(function() { $('#one').before('<p>This is before()</p>'); $('#two').after('<p>This is after()</p>'); $( "<p>this is insertBefore()</p>" ).insertBefore( "#three" ); $( "<p>this is insertAfter()</p>" ).insertAfter( "#four" ); });
<!-- We can specify where in the DOM we insert an element with the .before() and .after() functions. The syntax looks like this: $('target').after('<tag>To add</tag>'); Where 'target' is the element after which you want to add something and the bit between <tag>s is the HTML element you want to add. You can add <h1>s, <div>s, or any other valid HTML you like. --> <!DOCTYPE html> <html> <head> <title>Result</title> <script type='text/javascript' src='script.js'></script> </head> <body> <div class="container"> <h2>Greetings</h2> <div id="one">Div #1</div> <div id="two">Div #2</div> <div id="three">Div #3</div> <div id="four">Div #4</div> </div> </body> </html>