Inserting Content Before, After, and Inside Elements with jQuery

Part of the jQuery For Dummies Cheat Sheet

jQuery provides you with easy ways to get at the data in your Web page. In particular, you can insert any content you want, anywhere on your page. The examples that follow all use this sample code:

<html>
<head>
<title>My Test Page</title>
<script type="text/javascript" src="js/jquery-1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//Your code goes here.
}); </script> </head> <body> <div>I am a div.</div> <br /> <input value="Go" type="submit"> </body> </html>

Here's a quick rundown on how to insert content before, after, and inside a <div> element in a Web page:

To Place Content Code
In front of and outside the <div> (before) $(":submit").click(function () {
$("div").before("Before<br />");
});
In back of and outside the <div> (after) $(":submit").click(function () {
$("div").after("After<br />");
});
Inside the <div> but before existing content (prepend) $(":submit").click(function () {
$("div").prepend("New Content!");
});
Inside the <div> but after existing content (append) $(":submit").click(function () {
$("div").append("New Content!");
});
blog comments powered by Disqus

SERIES
jQuery For Dummies Cheat Sheet

Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.