Bytor the jQuery Dog

before(), after(), prepend(),append(),prependTo(), appendTo()

by Paul Leech

HTML

<script src="//code.jquery.com/jquery-1.11.0.js"></script>
<div id="a1" class='a'>A</div>
<div id="b1" class='b'>B</div>
<hr/>
<!--
<div class='c c1'>C</div>
<div class='d d1'>D</div>
-->
<hr/>
<div id="a2" class='a'>A</div>
<div id="b2" class='b'>B</div>
<!--
<div class='c c2'>C</div>
<div class='d d2'>D</div>
-->
<hr/>
<div id="a3" class='a'>A</div>
<div id="b3" class='b'>B</div>
<!--
<div class='c c3'>C</div>
<div class='d d3'>D</div>
-->
<hr/>
<div class='a a4'>A</div>
<div class='b b4'>B</div>
<!--
<div class='c c4'>C</div>
<div class='d d4'>D</div>
-->
<div id="a4" class='a'>A</div>
<div id="b4" class='b'>B</div>
<hr>
<div id="a5" class='a'>A</div>
<div id="b5" class='b'>B</div>
<hr>
<div id="a6" class='a'>A</div>
<div id="b6" class='b'>B</div>


<button id="AafterB">A after B</button>
<button id="AappendB">A append B</button>
<button id="AappendToB">A appendTo B</button>
<button id="AprependB">A prepend B</button>
<button id="AprependToB">A prependTo B</button>
<button id="AbeforeB">A before B</button>
<!--
<button id="AafterD">B after D</button>
<button id="AappendD">A append D</button>
<button id="BappendToC">B appendTo C</button>
<button id="BappendC">B append C</button>
-->
<button id="reload">Reload</button>

CSS

html { font-family:sans-serif; }
div {padding:3px;margin:3px;text-align:center;color:#fff;}

.a{border:solid 1px red;background:red;}
.b{border:solid 1px blue;background:blue;}
.c{border:solid 1px green;background:green}
.d{border:solid 1px maroon;background:maroon;}

JavaScript

$('#AafterB').click(function(){
	// alert($(this).attr('id'));
	$('#b1.b').after($('#a1.a').text('A is placed with .after()'));
});
$('#AappendB').click(function(){
	$('#b2.b').append($('#a2.a').text('A is placed with .append()'));
});
$('#AappendToB').click(function(){
	$('#b3.b').appendTo($('#a3.a').text('A is placed with .appendTo()'));
});
$('#AprependB').click(function(){
	$('#b4.b').prepend($('#a4.a').text('A is placed with .prepend()'));
});
$('#AprependToB').click(function(){
	$('#b5.b').prependTo($('#a5.a').text('A is placed with .prependTo()'));
});
$('#AbeforeB').click(function(){
	$('#b6.b').before($('#a6.a').text('A is placed with .before()'));
});


/*
$('#BafterA').click(function(){
	$('#a2.a').after($('#b2.b').text('B is placed with .after()'));
});
*/
$('#BappendA').click(function(){
	$('.a').append($('.b').text('B is placed with .append()'));
});

$('#reload').click(function(){
	location.reload();
});