The jQuery before() method is used to insert content before the selected elements.
The following example will insert a paragraph before the container element on document ready, whereas insert an image before the <h1> element on button click.
Example
<script>
$(document).ready(function(){
// Add content before an element with ID container
$("#container").before("<p>— The Beginning —</p>");
// Add content before headings
$("button").click(function(){
$("h1").before('<img src="images/marker-left.gif" alt="Symbol">');
});
});
</script>
Note: The contents or elements inserted using the jQuery before() and after() methods is added outside of the selected elements.
jQuery after() Method
The jQuery after() method is used to insert content after the selected elements.
The following example will insert a paragraph after the container element on document ready, whereas insert an image after the <h1> element on button click.
Example
<script>
$(document).ready(function(){
// Add content after an element with ID container
$("#container").after("<p>— The End —</p>");
// Add content after headings
$("button").click(function(){
$("h1").after('<img src="images/marker-right.gif" alt="Symbol">');
});
});
</script>
Insert Multiple Elements with before() & after() Method
The jQuery before() and after() also supports passing in multiple arguments as input. The following example will insert a <h1>, <p> and an <img> element before the <p> elements.
Example
<script>
$(document).ready(function(){
var newHeading = "<h2>Important Note:</h2>";
var newParagraph = document.createElement("p");
newParagraph.innerHTML = "<em>Lorem Ipsum is dummy text...</em>";
var newImage = $('<img src="images/smiley.png" alt="Symbol">');
$("p").before(newHeading, newParagraph, newImage);
});
</script>
jQuery wrap() Method
The jQuery wrap() method is used to wrap an HTML structure around the selected elements.
The jQuery code in the following example will wrap the container elements with a <div> element with the class .wrapper on document ready, whereas wrap all the inner content of the paragraph elements first with the <b> and again with <em> element.
Example
<script>
$(document).ready(function(){
// Wrap elements with class container with HTML
$(".container").wrap('<div class="wrapper"></div>');
// Wrap paragraph's content with HTML
$("button").click(function(){
$("p").contents().wrap("<em><b></b></em>");
});
});
</script>