Main Tutorials

jQuery before() and insertBefore() example

Both jQuery before() and insertBefore() methods are doing the same task, add a text or html content before the matched elements. The major difference is in the syntax.

For example,


<div class="prettyBox">I'm a ipman</div>
<div class="prettyBox">I'm a ipman 2</div>

1. $(‘selector’).before(‘new content’);


$('.prettyBox').before("<div class='newPrettybox'>Iron man</div>");

2. $(‘new content’).insertBefore(‘selector’);


$("<div class='newPrettybox'>Iron man</div>").insertBefore('.prettyBox');

Result

Both methods above are doing the same task, but with different syntax, the new contents after before() or insertBefore() will become


<div class='newPrettybox'>Iron man</div>
<div class="prettyBox">
   I'm a ipman
</div>

<div class='newPrettybox'>Iron man</div>
<div class="prettyBox">
   I'm a ipman 2
</div>

Try it yourself


<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	.prettyBox{
		padding:8px;
		background: grey;
		margin-bottom:8px;
		width:300px;
		height:100px;
	}
	.newPrettybox{
		padding:8px;
		background: red;
		margin-bottom:8px;
		width:200px;
		height:50px;
	}
</style>

</head>
<body>
  <h1>jQuery before() and insertBefore() example</h1>

  <div class="prettyBox">Ip man</div>
  
  <div class="prettyBox">Ip man 2</div>
  
  <p>
  <button id="before">before()</button>
  <button id="insertBefore">insertBefore()</button>
  <button id="reset">reset</button>
  </p>
  
<script type="text/javascript">
	
    $("#before").click(function () {
		
	  $('.prettyBox').before("<div class='newPrettybox'>Iron man</div>");
	  
    });
	
	$("#insertBefore").click(function () {
		
	  $("<div class='newPrettybox'>Iron man</div>").insertBefore('.prettyBox');
	  
    });
	
	$("#reset").click(function () {
	  location.reload();
    });
	
</script>
</body>
</html>

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments