jQuery

jQuery Prepend Example

The aim of this example is to explain and use the .prepend() method of jQuery.

This method will allow you to insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

It is similar to the .append() method, except that the .append() method inserts content at the end of the selected elements.

It stands as a very useful tool when content is needed to be added dynamically in full interaction with the user, like on a user click, mouseover etc.

The .prepend() method inserts the specified content as the first child of each element in the jQuery collection.

1. The Basics

The following section is about setting up you HTML document and becoming familiar with the basic syntax of the method.

1.1 Document Setup

To begin, create a new HTML document and add the following basic syntax inside:

<!DOCTYPE html>
<html>
<head>
	<title>jQuery Prepend Example</title>
</head>
<body>

<!-- HTML SECTION  -->


<!-- JAVASCRIPT SECTION  -->
<script src="jquery-1.11.3.min.js"></script>

<script type="text/javascript">

</script>

</body>
</html>

As you can see, the document is structured in two setions, the HTML section and JS section where respective code is going to be added. Also, notice that the jQuery library is linked locally and you may have to download it, by following this link.

1.2 Method’s Basic Syntax

Before looking at examples and the application of the method, let’s see the basic syntax:

$(selector).prepend(content,function(index,html)); where:

content – Required. Specifies the content to insert (can contain HTML tags). It may be HTML, jQuery or DOM element/s.
function(index,html) – Optional. Specifies a function that returns the content to insert.
index returns the position of the element in the set, while html returns the current HTML of the selected element.

2. Cases and Examples

Now let’s see some useful applications of the method.

2.1 The Basic Example

In this first example, we’re just going to append a new paragraph in a div element. So first, just add a new div in you HTML section.

<!-- HTML SECTION  -->

<div>A paragraph is going to be added before me.</div>

Before continuing with jQuery, let’s prestyle the div and the p:

<style type="text/css">
body {
    width: 20%;
}
div {
    border: 1px solid blue;
    padding: 0.5em;
}
p {
    border: 1px solid red;
    padding: 0.5em;
}
</style>

In the JS section, select the div element and apply the prepend method as follows:

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">
$(document).ready(function(){
    $("div").prepend("<p>I was added with jQuery inside this div</p>");
});
</script>

The result before and after would be:

Prepend - A Basic Example
Prepend – A Basic Example

2.2 Create content with HTML, jQuery and DOM

There are three ways you can create content using javascript. In this example, these methods of inserting elements are used to prepend paragraphs on a button click.

<p>This is a paragraph.</p>

<button onclick="prependText()">Prepend text</button>

Next, in JS, we create a function called prependText() which will handle the three ways of inserting content and prepend it to the paragraph element that already exists in HTML:

<script type="text/javascript">
    function prependText() {
    var txt1 = "<p>Text.</p>";              // Create text with HTML
    var txt2 = $("<p></p>").text("Text.");  // Create text with jQuery
    var txt3 = document.createElement("p");
    txt3.innerHTML = "Text.";               // Create text with DOM
    $("p").prepend(txt1, txt2, txt3);       // Prepend new elements
}
</script>

The result, as expected would be content addition on the click of the button:

Creating content with HTML, jQuery and DOM
Creating content with HTML, jQuery and DOM

2.3 Prepend Content using a Function

In this last example, we aim to use a function to insert content at the beginning of the selected elements. First add two lines of text as a pragraph and a button on the click of which, content is going to be added.

<p>I am the first paragraph here.</p>
<p>I am just another paragraph.</p>
<button>Insert Content</button>

In jQuery, after making sure we have a click handler for the button, we apply the method to the p element using a function as an argument which will return a line of text with the index of the current element.

<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        $("p").prepend(function(n){
            return "<b>This p element has index " + n + "</b>. ";
        });
    });
});
</script>

The result in the browser would be:

Prepending content using a function.
Prepending content using a function.

3. Conclusion

To conclude, the .prepend() method plays a crucial role when it comes to inserting HTML before some selected element. You may have also used .prependTo(). The .prepend() and .prependTo() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target.

With .prepend(), the selector expression preceding the method is the container into which the content is inserted. With .prependTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

4. Download

Download
You can download the full source code of this example here: jQuery Prepend

Fabio Cimo

Fabio is a passionate student in web tehnologies including front-end (HTML/CSS) and web design. He likes exploring as much as possible about the world wide web and how it can be more productive for us all. Currently he studies Computer Engineering, at the same time he works as a freelancer on both web programming and graphic design.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button