Adding Elements to the Page in jQuery

How to add content to a page using the jQuery methods prepend(), prependTo(), append(), appendTo(), before(), insertBefore(), after(), insertAfter(), wrap(), wrapAll() and wrapInner().

jQuery Logo

One of the lovely things about jQuery is that it makes it really easy to manipulate content in the page. With just a few method calls, you can quickly add, remove, and replace page elements, as well as move elements around the page's DOM tree.

In this tutorial you explore various jQuery methods for adding new content to the page. You look at:

As well as using the above methods, you can also add new content to an element using the html() and text() methods. Find out more in Accessing Element Content with jQuery.

The tutorial's quite lengthy, but once you understand the basic concepts you'll find that all the methods work in a similar way. You'll also find lots of code examples to make things clear. So let's get started!

Adding new content at the start of an element: prepend()

The prepend() method adds some content at the start of an element (or elements). In other words, it adds the content as the first child (or children) of the target element(s).

You pass the content as an argument to prepend(). The argument can be any of the following:

  • An element object that you've created using a JavaScript DOM function such as document.getElementById() or document.createElement()
  • A string of HTML representing the content that you want to add
  • A jQuery object containing the element(s) to insert
  • A callback function that should return the HTML for the element(s) to insert

The following examples show how to use prepend() with each of these types of arguments.

Using prepend() with an element object

This first example creates a new paragraph element using the JavaScript DOM functions, then inserts this new paragraph element before the existing paragraph in the #myDiv element:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  var newPara = document.createElement( 'p' );
  var newParaText = document.createTextNode( "Here's some new text" );
  newPara.appendChild( newParaText );
  $('#myDiv').prepend( newPara );
}

</script>

</head>
<body>
  <div id="myDiv">
    <p>Existing paragraph</p>
  </div>
</body>
</html>

After running the above code, the page's content changes to this:


<body>
  <div id="myDiv">
    <p>Existing paragraph</p>
    <p>Here's some new text</p>
  </div>
</body>

Using prepend() with an HTML string

The second example achieves the same effect as the first by passing a string of HTML, rather than creating the paragraph element with the DOM functions. As you can see, this approach is much less long-winded:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  $('#myDiv').prepend( "<p>Here's some new text</p>" );
}

</script>

</head>
<body>
  <div id="myDiv">
    <p>Existing paragraph</p>
  </div>
</body>
</html>

Using prepend() with a jQuery object

This next prepend() example achieves the same result as the first 2 examples by passing a jQuery object containing an element to insert. First, it creates the paragraph element to insert, then it calls prepend() to insert the paragraph:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  var newPara = $( "<p>Here's some new text</p>" );
  $('#myDiv').prepend( newPara );
}

</script>

</head>
<body>
  <div id="myDiv">
    <p>Existing paragraph</p>
  </div>
</body>
</html>

Notice that you can create new HTML elements simply by passing a string of HTML to the jQuery ($) function. Very handy!

Using prepend() with a callback function

As with many other jQuery methods, you can pass a callback function to prepend(). This allows you to prepend dynamically-generated content based on the existing element's position in the set, its existing content, or other factors.

Your callback function should accept 2 arguments:

  • The index position of the current element in the set (starting from zero)
  • The old HTML contents of the current element

The function should return the content to prepend to the element, as an HTML string.

Here's an example that uses a callback function to prepend a sequential number to the h1 heading within each of 3 divs in the page:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  $('.myDiv>h1').prepend( addHeadingNumber );
}

function addHeadingNumber( index, oldMarkup ) {
  return ( (index+1) + '. ' );
}

</script>

</head>
<body>
  <div class="myDiv">
    <h1>First Heading</h1>
    <p>First paragraph</p>
  </div>
  <div class="myDiv">
    <h1>Second Heading</h1>
    <p>Second paragraph</p>
  </div>
  <div class="myDiv">
    <h1>Third Heading</h1>
    <p>Third paragraph</p>
  </div>
</body>
</html>

After running the above code, the page's content changes to this:


<body>
  <div class="myDiv">
    <h1>1. First Heading</h1>
    <p>First paragraph</p>
  </div>
  <div class="myDiv">
    <h1>2. Second Heading</h1>
    <p>Second paragraph</p>
  </div>
  <div class="myDiv">
    <h1>3. Third Heading</h1>
    <p>Third paragraph</p>
  </div>
</body>

Calling prepend() on multiple elements

Finally, what happens if you select more than 1 element, then call prepend() on the resulting set of elements? The answer is that jQuery inserts the supplied content at the start of each of the elements. For example, the following code inserts the paragraph "Here's some new text" at the start of all 3 div elements in the page:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  $('.myDiv').prepend( "<p>Here's some new text</p>" );
}

</script>

</head>
<body>
  <div class="myDiv">
    <p>Existing paragraph</p>
  </div>
  <div class="myDiv">
    <p>Existing paragraph</p>
  </div>
  <div class="myDiv">
    <p>Existing paragraph</p>
  </div>
</body>
</html>

After running the above code, the page's content changes to:


<body>
  <div class="myDiv">
    <p>Here's some new text</p>
    <p>Existing paragraph</p>
  </div>
  <div class="myDiv">
    <p>Here's some new text</p>
    <p>Existing paragraph</p>
  </div>
  <div class="myDiv">
    <p>Here's some new text</p>
    <p>Existing paragraph</p>
  </div>
</body>

prependTo(): An alternative to prepend()

prependTo() does essentially the same job as prepend(): it inserts content at the start of an element or elements. The main difference between the 2 methods is in the syntax:

  • prepend() inserts the content specified in the argument into the element(s) contained in the jQuery object on which prepend() was called.
  • prependTo() takes the element(s) contained in the jQuery object on which prependTo() was called, and inserts them into the element(s) specified in the argument.

In other words, you can think of prependTo() as the mirror image of prepend(). The following 2 lines of code both do the same thing:


$('#myDiv').prepend( "<p>Here's some new text</p>" );
$("<p>Here's some new text</p>").prependTo( '#myDiv' );

prependTo() can take either of the following as an argument:

  • A selector that selects the element(s) to prepend the content to.
  • A jQuery object that contains the element(s) to prepend the content to.

As with prepend(), if you pass multiple elements to prependTo() then the content is inserted at the start of each element.

Here's an example that shows how to use prependTo() with selectors and with jQuery objects:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  var existingContent = $("<div><p>Existing text</p></div>");
  var newContent = $("<p>Here's some new text</p>");
  newContent.prependTo( existingContent );
  existingContent.prependTo( '#myDiv' );
}

</script>

</head>
<body>
  <div id="myDiv">
  </div>
</body>
</html>

After running the above code, the page's content changes to this:


<body>
  <div id="myDiv">
    <div>
      <p>Here's some new text</p>
      <p>Existing text</p>
    </div>
  </div>
</body>

Here's how it works. First the code creates a jQuery object, existingContent, using an HTML string to generate and store a div element and a p element. Then it creates another jQuery object, newContent, that contains the new p element to be prepended to the div inside existingContent.

Next, the code calls prependTo() on newContent, passing in existingContent. This adds the p element in newContent to the start of the div element in existingContent. existingContent's div now contains both paragraphs of text.

Finally, the code calls prependTo() on the final existingContent object, passing in a selector string to select the #myDiv div element in the page. This inserts the existingContent div (and the 2 paragraphs of text inside it) at the start of #myDiv's content.

Adding new content at the end of an element: append() and appendTo()

append() and appendTo() work in exactly the same way as prepend() and prependTo(), except that they insert the content as the last child of the target element(s), instead of the first child.

Here's an example script that shows various ways to call append() and appendTo():


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {

  // Append a DOM element object
  var newPara = document.createElement( 'p' );
  var newParaText = document.createTextNode( "Here's a DOM element" );
  newPara.appendChild( newParaText );
  $('#myDiv').append( newPara );

  // Append a string of HTML
  $('#myDiv').append( "<p>Here's a string of HTML</p>" );

  // Append a jQuery object
  $('#myDiv').append( $("<p>Here's a jQuery object</p>") );

  // Append the output from a callback function
  $('#myDiv').append( sayHello );

  function sayHello() {
    return "<p>Hello! This is the output from a callback function</p>";
  }

  // Append some content using appendTo()
  $("<p>Here's some content appended using appendTo()</p>").appendTo('#myDiv');
}

</script>

</head>
<body>
  <div id="myDiv">
    <p>Existing paragraph</p>
  </div>
</body>
</html>

After running the above code, the page's content changes to the following:


<body>
  <div id="myDiv">
    <p>Existing paragraph</p>
    <p>Here's a DOM element</p>
    <p>Here's a string of HTML</p>
    <p>Here's a jQuery object</p>
    <p>Hello! This is the output from a callback function</p>
    <p>Here's some content appended using appendTo()</p>
  </div>
</body>

Adding new content before an element: before() and insertBefore()

before() and insertBefore() are very similar to prepend() and prependTo(). The main difference is that, whereas prepend() and prependTo() insert content at the start of an element, before() and insertBefore() insert content directly before an element.

As with the other methods in this tutorial, you can call before() and insertBefore() on a set of elements to add the new content before each of the elements in the set.

before()

before() takes some content as an argument, and inserts it before the element(s) in the jQuery object. As with prepend(), this content can be an element object, a string of HTML, a jQuery object containing elements, or a callback function that returns the HTML for the content to insert.

Unlike prepend(), the callback function can't accept any arguments such as the existing element's index position or HTML.

Here's an example script that shows various ways to use before():


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {

  // Insert a DOM element object
  var newPara = document.createElement( 'p' );
  var newParaText = document.createTextNode( "Here's a DOM element" );
  newPara.appendChild( newParaText );
  $('#myDiv').before( newPara );

  // Insert a string of HTML
  $('#myDiv').before( "<p>Here's a string of HTML</p>" );

  // Insert a jQuery object
  $('#myDiv').before( $("<p>Here's a jQuery object</p>") );

  // Insert the output from a callback function
  $('#myDiv').before( sayHello );

  function sayHello() {
    return "<p>Hello! This is the output from a callback function</p>";
  }

}

</script>

</head>
<body>
  <div id="myDiv">
    <p>Existing paragraph</p>
  </div>
</body>
</html>

After running the above code, the page's content changes to this:


<body>
  <p>Here's a DOM element</p>
  <p>Here's a string of HTML</p>
  <p>Here's a jQuery object</p>
  <p>Hello! This is the output from a callback function</p>
  <div id="myDiv">
    <p>Existing paragraph</p>
  </div>
</body>

insertBefore()

insertBefore() is to before() what prependTo() is to prepend(). Whereas before() accepts the content to insert as an argument, insertBefore() accepts the element(s) to insert the content into as an argument.

Here's the prependTo() example from earlier in the tutorial, modified to use insertBefore() instead. This creates a jQuery object with some content, inserts some new content before it, then inserts the resulting content before the div in the page:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  var existingContent = $("<div><p>Existing text</p></div>");
  var newContent = $("<p>Here's some new text</p>");
  newContent.insertBefore( existingContent );
  existingContent.insertBefore( '#myDiv' );
}

</script>

</head>
<body>
  <div id="myDiv">
  </div>
</body>
</html>

After running the above code, the page's content changes to the following (compare this to the content generated by the prependTo() example):


<body>
  <p>Here's some new text</p>
  <div><p>Existing text</p></div>
  <div id="myDiv">
  </div>
</body>

Adding new content after an element: after() and insertAfter()

As you can probably guess by now, after() and insertAfter() are identical to before() and insertBefore(), except that they insert content directly after an element (or each element in a set of elements).

The following example script shows various ways to use after() and insertAfter():


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {

  // Insert a DOM element object
  var newPara = document.createElement( 'p' );
  var newParaText = document.createTextNode( "Here's a DOM element" );
  newPara.appendChild( newParaText );
  $('#myDiv').after( newPara );

  // Insert a string of HTML
  $('#myDiv').after( "<p>Here's a string of HTML</p>" );

  // Insert a jQuery object
  $('#myDiv').after( $("<p>Here's a jQuery object</p>") );

  // Insert the output from a callback function
  $('#myDiv').after( sayHello );

  function sayHello() {
    return "<p>Hello! This is the output from a callback function</p>";
  }

  // Append some content using insertAfter()
  $("<p>Here's some content inserted using insertAfter()</p>").insertAfter('#myDiv');
}

</script>

</head>
<body>
  <div id="myDiv">
    <p>Existing paragraph</p>
  </div>
</body>
</html>

And here's how the page content looks after running the script — notice how the order of the inserted elements is reversed, because after() and insertAfter() insert each element directly after #myDiv each time:


<body>
  <div id="myDiv">
    <p>Existing paragraph</p>
  </div>
  <p>Here's some content inserted using insertAfter()</p>
  <p>Hello! This is the output from a callback function</p>
  <p>Here's a jQuery object</p>
  <p>Here's a string of HTML</p>
  <p>Here's a DOM element</p>
</body>

Wrapping new content around existing content: wrap(), wrapAll() and wrapInner()

The last methods you'll look at in this tutorial let you wrap new content around existing content:

  • wrap() wraps an HTML structure around an existing element or elements. If wrapping around multiple elements, the structure is wrapped around each element in the set.
  • wrapAll() is similar to wrap(). However, if wrapping around multiple elements, the structure is wrapped around the whole set, rather than around individual elements.
  • wrapInner() wraps an HTML structure around the contents of an element or elements.

wrap()

wrap() takes an HTML structure and wraps it around an existing element (or set of elements). If you call wrap() on a jQuery object containing multiple elements, the HTML structure is wrapped around each individual element.

wrap()'s syntax is the same as that of before() and after(), so you can pass it an element object, a string of HTML, a jQuery object containing elements, or a callback function that returns the HTML structure.

Your HTML structure can be as simple as a single element (such as a div), or it can contain multiple nested elements. However, if it contains nested elements then there should only be 1 innermost element. (If there were more than 1 innermost element then wrap() wouldn't know which element to wrap the existing content in.)

Here's an example script showing various ways to call wrap():


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {

  // Wrap a DOM element object around #myDiv
  var newDiv = document.createElement( 'div' );
  newDiv.id = "newDiv1";
  $('#myDiv').wrap( newDiv );

  // Wrap a string of HTML around #myDiv
  $('#myDiv').wrap( '<div id="newDiv2" />' );

  // Wrap a jQuery object around #myDiv
  $('#myDiv').wrap( $('<div id="newDiv3" />') );

  // Wrap the output from a callback function around #myDiv
  $('#myDiv').wrap( generateDiv );

  function generateDiv() {
    return '<div id="newDiv4" />';
  }

  // Wrap a nested HTML structure around #myDiv
  $('#myDiv').wrap( '<div id="outer"><div id="inner"></div></div>' );

}

</script>

</head>
<body>
  <div id="myDiv">
    <p>Existing paragraph</p>
  </div>
</body>
</html>

After running the above script, the page's content looks like this:


<body>
  <div id="newDiv1">
    <div id="newDiv2">
      <div id="newDiv3">
        <div id="newDiv4">
          <div id="outer">
            <div id="inner">
              <div id="myDiv">
                <p>Existing paragraph</p>
              </div>
            </div>
          </div>
        </div> 
      </div>
    </div>
  </div>
</body>

Each new div is added inside the last div that was added, because the script calls wrap() on #myDiv (the innermost div) each time.

wrapAll()

wrapAll() works just like wrap(), with 2 differences:

  • If you call wrapAll() on a set of multiple elements then the HTML structure is wrapped once around the entire set, rather than around each element.
  • You can't use a callback function with wrapAll().

The following example shows the difference between wrap() and wrapAll() when used on a set of multiple elements:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {

  // Wrap a div around #myDiv1 and another div around #myDiv2
  $('.type1').wrap( '<div class="newDiv1" />' );

  // Wrap a single div around #myDiv3 and #myDiv4
  $('.type2').wrapAll( '<div class="newDiv2" />' );
}

</script>

</head>
<body>

  <div id="myDiv1" class="type1">
    <p>Existing paragraph</p>
  </div>
  <div id="myDiv2" class="type1">
    <p>Existing paragraph</p>
  </div>

  <div id="myDiv3" class="type2">
    <p>Existing paragraph</p>
  </div>
  <div id="myDiv4" class="type2">
    <p>Existing paragraph</p>
  </div>

</body>
</html>

After running the above script, the page's content looks like this:


<body>

  <div class="newDiv1">
    <div id="myDiv1" class="type1">
      <p>Existing paragraph</p>
    </div>
  </div>
  <div class="newDiv1">
    <div id="myDiv2" class="type1">
      <p>Existing paragraph</p>
    </div>
  </div>

  <div class="newDiv2">  
    <div id="myDiv3" class="type2">
      <p>Existing paragraph</p>
    </div>
    <div id="myDiv4" class="type2">
      <p>Existing paragraph</p>
    </div>
  </div>
  
</body>

Notice that the "type1" divs (#myDiv1 and #myDiv2) have new divs wrapped around each of them, while the "type2" divs (#myDiv3 and #myDiv4) have a single div wrapped around them both.

wrapInner()

wrapInner() works just like wrap(), except that it wraps the HTML structure around the contents of the target element(s), rather than the target element(s) themselves. Here's an example script that shows the difference between wrap() and wrapInner():


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {

  // Wrap a div around #myDiv1
  $('#myDiv1').wrap( '<div id="newDiv1" />' );

  // Wrap a div around the contents of #myDiv2
  $('#myDiv2').wrapInner( '<div id="newDiv2" />' );
}

</script>

</head>
<body>

  <div id="myDiv1">
    <p>Existing paragraph</p>
  </div>

  <div id="myDiv2">
    <p>Existing paragraph</p>
  </div>

</body>
</html>

After running the above script, the page's content looks like this:


<body>

  <div id="newDiv1">
    <div id="myDiv1">
      <p>Existing paragraph</p>
    </div>
  </div>

  <div id="myDiv2">
    <div id="newDiv2">
      <p>Existing paragraph</p>
    </div>
  </div>

</body>

As you can see, while the call to wrap() has wrapped #newDiv1 around the outside of #myDiv1, the call to wrapInner() has wrapped #newDiv2 around the contents of #myDiv2 — that is, around the paragraph inside #myDiv2.

Summary

In this tutorial you've explored various ways to insert new content into the page with jQuery. You've looked at using:

  • prepend() and prependTo() to add content as the first child of an element (or elements)
  • append() and appendTo() to add content as the last child of an element (or elements)
  • before() and insertBefore() to add content before an element (or elements)
  • after() and insertAfter() to add content after an element (or elements)
  • wrap(), wrapAll() and wrapInner() to wrap content around an element (or elements), or around an element's contents

In future tutorials I'll be showing you how to manipulate page content in other ways using jQuery, including moving, removing, and replacing elements. Until then, have fun coding with jQuery!

Follow Elated

Related articles

Responses to this article

4 responses (oldest first):

15-Feb-11 15:04
I would like to add a draggable() div to the page when a button/link is clicked.

When I attempt to do something like:

function addNewArea() {
var newDiv = $( "<div id='draggable3' class='ui-widget-content' >Here's some new div text</div>" );
$('#demo').append( newDiv );

var newScript = $( "<script>$(function(){$( '#draggable3' ).draggable();});</script>" );
$('#scriptArea').prepend( newScript );
}

Things go badly when it loads the page. Is there a good way to do this?
firebug is telling me:"unterminated string literal
var newScript = $( "<script>$(function(){$( \'#draggable3\' ).draggable();});"

and I get script displaying on the page. When I go to click my add div button it tells me that the addNewArea function is not defined. I am guessing that I need to rethink how I am doing this. Even if I could get the script added would the browser really see it without reloading?

Thank you for your help.








;
15-Feb-11 19:12
@Floyd: Woah, you're using JavaScript to generate JavaScript?

Just do it all with jQuery:


var newDiv = $( "<div id='draggable3' class='ui-widget-content' >Here's some new div text</div>" );
newDiv.draggable();
$('#demo').append( newDiv );


Cheers,
Matt
16-Feb-11 12:37
That works great.
Thank you
20-Feb-11 19:15
@Floyd: Good to hear.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page