jQuery .prepend() Method Examples
If you ever wanted to Insert content (text or html or both), specified by the parameter, to the beginning of each element in the set of matched elements, then using the jQuery prepend method is an excellent option. In this article, I am going to share easy examples on how to use the .prepend() method.
How to use jQuery prepend method
Bacially, the prepend() method in jQuery adds the content before the content of the target. So let’s see how to use it with a simple, easy to follow example. This example assumes that we have 2 divs with class “red” & “green” applied to them. Apart from that, these divs are held in another “container” div for easy manipulation. So what we are going to do is have 2 individual buttons that will let you prepend the red div to green div and vice-versa. We also have another button that will reset the divs back to their original state, once the prepend method has been used on them dynamically.
Example: Using the prepend method in jQuery to add content before the content of the target begins
<html>
<head>
<title>Exmaples of using the .prepend() method</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<style type="text/css">
.red {
background-color: #FFA6A6;
border: 1px solid red;
margin: 10px;
}
.green {
background-color: #CEFFCE;
border: 1px solid green;
margin: 10px;
}
</style>
</head>
<body>
<div class="divs_container">
<div id="mydiv1" class="red">This is my 1 div</div>
<div id="mydiv2" class="green">This is my 2 div</div>
</div>
<input type="button" name="sbt_prepend_g2r" id="sbt_prepend_g2r" value="Prepend Green Div to Red">
<input type="submit" name="sbt_remove" id="sbt_remove" value="Undo">
<input type="button" name="sbt_prepend_r2g" id="sbt_prepend_r2g" value="Prepend Red Div to Green">
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
var divs_container_html = $(".divs_container").html();
//Prepend Green Div to Red
$('#sbt_prepend_g2r').on("click", function(){
$('.red').prepend($('.green'));
});
//Prepend Red Div to Green
$('#sbt_prepend_r2g').on("click", function(){
$('.green').prepend($('.red'));
});
//Reset the divs back to their original state
$('#sbt_remove').on("click", function(){
$(".divs_container").html(divs_container_html);
});
});
</script>
</body>
</html>Simple, isn’t it?
Do you know of any other ways to use the jQuery prepend() method? Feel free to suggest by commenting below.