jQuery

jQuery after Examples

jQuery after is an easy to use method provided by jQuery. If you want to insert text or any other content, after the end of an element, then .after() method is for you. In this article, I am going to share info on the after() method along with easy to follow examples.

How to use the jQuery after() method

Let’s consider an example. This example assumes that we have few divs with class applied to each of them & these divs are held in another “container” div for easy manipulation. So what we are going to do is have an individual button that will let you add content after the red and orange div. We also have another button that will reset the div back to their original state, once the jquery after method has been used on them dynamically.

Example: Here is the complete source code to use the .after() method in jQuery

<html>
<head>
<title>jQuery .after() method Examples</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;
}
.grey {
background-color: #EEEEEE;
border: 1px solid #CCC;
margin: 10px;
}
.orange {
background-color: #FF9900;
border: 1px solid #F60;
margin: 10px;
}
.blue {
background-color: #0099FF;
border: 1px solid #06C;
margin: 10px;
}
.purple {
background-color: #9966FF;
border: 1px solid #90F;
margin: 10px;
}
</style>
</head>

<body>

<div class="divs_container">

<div id="mydiv1" class="red">
This is my 1 div

<div id="mydiv2" class="green">
This is my 2 div
</div>

</div>

<div id="mydiv3" class="grey">
This is my 3 div
</div>

<p>&nbsp;</p>

<div id="mydiv4" class="orange">
This is my 4 div

<div id="mydiv5" class="blue">
This is my 5 div
</div>

<div id="mydiv6" class="purple">
This is my 6 div
</div>

</div>

</div>

<input type="button" name="sbt_after_green" id="sbt_after_green" value="Add Grey Div after Green">

<input type="submit" name="sbt_remove" id="sbt_remove" value="Undo">

<input type="button" name="sbt_after_orange" id="sbt_after_orange" value="Add Purple Div after Orange">

<script type="text/javascript" language="javascript" >

$(document).ready(function(){

var divs_container_html = $(".divs_container").html();

//Add Grey Div after Green
$('#sbt_after_green').on("click", function(){

$('.green').after($('.grey'));

});

//Add Purple Div after Orange div
$('#sbt_after_orange').on("click", function(){

$('.orange').after($('.purple'));

});

//Reset the divs back to their original state
$('#sbt_remove').on("click", function(){

$(".divs_container").html(divs_container_html);

});

});

</script>
</body>
</html>
That’s it for now!

Do you know of any other ways to use .after() method using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*