1. Home
image

jQuery Tutorial Concepts - From Beginner to Pro

Learn jQuery from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 19
  • 3
right-top-arrow
13

jQuery append() Method

Updated on 20/08/2024447 Views

Imagine a site where everything is static and lacks interactivity. Pressing buttons do not yield any results while the elements remain fixed on the page. jQuery is what comes in place right here, bridging gap between static HTML and dynamic web experiences.

Specifically intended to ease DOM (Document Object Model) manipulation, jQuery is a powerful JavaScript library. This DOM acts as a blueprint of a webpage, defining how elements are organized and displayed. It allows us to influence web pages by making them more interactive; thus, we can add or remove elements or modify them depending on user interaction or other events.

The Art of Appending: Adding Content with jQuery

Think of appending as adding information to an existing element within DOM. Such additional content may contain texts, images, or entire HTML structures. For this, we have the append() method provided in jQuery, which performs such functions.

Basic Syntax and Usage:

Let us take a peek at the basic syntax for appending content below:

JavaScript

$(selector).append(content);

In this code snippet:

  • $(selector): This is the part where you specify what part in the DOM you want to add the new content to. You may choose selectors, for example, IDs, classes, or element tags to be more specific to the selected element(s).
  • .append(content): The append() method is exactly the one. In the parentheses, specify the content you want to append. This content can be:
  • HTML Strings: You can also put the append HTML jQuery code in the quotes to make new elements.
  • Existing DOM Elements: Use jQuery selectors to find the elements on the page that are already present and then append them to the new location.
  • Text Content: Just type the text in double quotation marks to have it appear as plain text.

Example: The following code appends a new paragraph element with the text "Hello, World!" to a webpage element with the ID "container":

JavaScript

$("#container").append("<p>Hello, World!</p>");

Witnessing the Magic in Action

Let's see this concept come alive with a simple example. Consider the following HTML structure:

HTML

<!DOCTYPE html>

<html>

<body>

  <div id="message"></div>

  <button id="appendButton">Click Me</button>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  <script>

    $(document).ready(function() {

      $("#appendButton").click(function() {

        $("#message").append("Content appended on button click!");

      });

    });

  </script>

</body>

</html> 

In this example:

  • We use a jQuery append HTML in div element with the ID of "message" where we'll insert content.
  • The button that has an ID "appendButton" is in charge of triggering the appending activity.
  • The code in JavaScript used the function click() of jQuery to listen to clicks on the button.
  • Upon pressing the button, the append() method inserts the text "Content appended on button click!" into the jQuery append div element with ID "message."

Learning How to Use jQuery for Content Modification

The jQuery append function provides an unmatched level of power when it comes to dynamic insertion of contents to your web pages. This section deals with the different types of content you can use append() to bring, making the interface more interactive and engaging.

1. HTML Elements and Forms Creation

Here's a scenario. You need to add a new paragraph with some text content to your webpage. Via append(), you can dynamically create the HTML element using jQuery and then achieve this. Here's the code:

JavaScript

$(document).ready(function() {

$("#myContainer").append("<p>This is a new paragraph!</p>");

});

In this example:

  • $(document).ready(function() { ... }) allows the code to execute only when the document completes its loading.
  • $(#myContainer) selects the element with the ID "myContainer", the place where we want to put the new content.
  • .append("<p>This is a new paragraph!</p>") is a method that creates a new paragraph (<p>) with the text "This is a new paragraph!" and appends it to the end of the selection (#myContainer).
  • Visual Breakdown (): will append the paragraph element as the last child of the element with the ID "myContainer".

2. Text generation and Manipulation

You may also use the jQuery append method to append text directly. Here's an example:

JavaScript

$(document).ready(function() {

$("#myElement").append("Hello World!");

});

In this code snippet, the words "Hello World" are appended to the element with the ID "myElement". However, it is crucial to remember that append() does replace any existing content within the target element.

For more granular control over text content, you can utilize methods like .text() to set the text content or .html() to include HTML tags within the text:

JavaScript

$("#myElement").text("New Text Content"); // by .text()

$("#myElement").html("<b>Bold Text</b>"); // .html() usage for bold formatting

The above code snippet allows you to control the text within your elements to meet your customization needs.

3. Existing DOM Elements

For instance, if you want to move a specific element from one place to another on the page, just select it and drag it to the desired position. This is possible by selecting the element using the ‘append’ method to append it to the new target element. Here's an example:

JavaScript

$(document).ready(function() {

$("#elementToMove").appendTo("#newContainer");

});

In this example:

  • $("#elementToMove") chooses the element you would like to move.
  • .appendTo("#newContainer") is an abbreviated version of the .appendTo() method (which is equivalent to append() with the target selector) that takes the element with the ID "elementToMove" and appends it to the element with the ID "newContainer".

Thus, the moving of the existing element into the new container element will be achieved.

Visual Breakdown ():

This solution is aimed at changing the structure of the web page by rearranging elements in it without leaving the web page.

4. Cloned Elements

When you want to add multiple copies of an existing element, the .clone() method is the most efficient way to achieve this by creating clones of the existing element before appending. Here's an example:

JavaScript

$(document).ready(function() {

var myElement = $("#myElement").clone();

$("#targetContainer").append(myElement);

});

Here, we:

  • var myElement = $("#myElement").clone() is creating a copy of the element having the ID of "myElement".
  • $("#targetContainer").append(myElement), adds the cloned element to the element with the ID "targetContainer".

This way, you are sure that the element has not been changed and that you are working on a clean copy which you can append to the original.

Mastering the jQuery Append Function

The append() method is key to manipulating dynamic content in jQuery. It helps you to dynamically add various HTML elements, text content, and even existing DOM elements to a webpage. Let's discuss further how to use append() to create interesting and fun user interactions.

1. Adding Information to the Last Part

The most basic jQuery append function is inserting the content at the end of the selected element(s). Imagine you have a simple HTML structure like this:

HTML

<div id="container">

</div>

You can use jQuery to append a new paragraph element with some text at the bottom of the #container div:

JavaScript

($("#container").append("<p>This is the appended paragraph.</p>"));

This code selects the element with the ID "container" and then uses append() to add a new <p> element containing the text "This is the appended paragraph." The resulting HTML will look like this:

HTML

<div id="container">

<p>This is the appended paragraph.</p>

</div>

2. Chaining of Multiple append () Calls

The magic of jQuery is its capacity to connect methods and get a short and smooth code. You can utilize append() in a loop fashion to add many elements one after the other. For instance, consider this scenario:

JavaScript

$("#container").append("<h2>New Heading</h2>").append("<p>More appended content.</p>");

Here, we're linking two append() calls with a ',' in between. The first appends an <h2> element with the text "New Heading," and the second appends a <p> element containing "More appended content." The final HTML structure will reflect these additions:

HTML

<div id="container">

<h2>New Heading</h2>

<p>More appended content.</p>

</div>

3. Returning the Appended Element(s)

The append() method also goes beyond adding content but also provides a way for you to handle the new elements. It is normally a default behavior that doesn't return anything. On the other hand, .append() allows you to do that within a larger jQuery expression if you want to continue manipulating the appended element(s) further.

For example, suppose you want to add a class named "highlight" to the appended paragraph:

JavaScript

var newParagraph = $("<p>This is appended and highlighted.</p>").addClass("highlight");

$("#container").append(newParagraph);

Before, we utilized jQuery methods to generate a new paragraph, and we stored it in the new paragraph variable. We then give the element this class "highlight" using .addClass(). Eventually, we add newParagraph variable (that contains the whole <p> element) to #container element.

4. Conditional Appending Based on Criteria

Conditional statements such as if statements can be used to control when content is appended; append() can be used. This accounts for the responsiveness to scenarios that are specific. For instance, you have a button on your page, and you want to add a success message when the form is submitted correctly.

HTML

<button id="submitButton">Submit Form</button>

<div id="message"></div>

JavaScript

$("#submitButton").click(function() {

if (formValidate()) { // Replacing by your logic form validation }

$("#message").append("<p>Form submitted successfully!</p>");

}

});

In this example, clicking on the button causes a click event to transpire. Within the event handler, we first check if validateForm() function (use your actual validation logic instead) returns true. If the form is valid, we create a paragraph element with a success message and append it to the #message element.

Multiple Elements and Filtering: Working with Both

Adding content to a single element using append() is just great. However, its real power is demonstrated when it is used along with jQuery's powerful selectors for working with jQuery append multiple elements. This section deals with the multiple elements appending as well as targeted filtering for the insertions.

Appending to Multiple Elements

Suppose you have a website with a product list where you have multiple divs for each product in the product listing section. You need to have a "Buy Now" button on each individual product. Here's how to achieve this using append():

JavaScript

$('.product').append('<button class="buy-now">Buy Now</button>');

In this example:

  • $('.product') selects all elements that have the class "product" (assuming that each product is the one with this class).
  • .append('<button class="buy-now">Buy Now</button>') will add a button element with the class "buy-now" that contains the text "Buy Now" at the end of each product element that was selected.

This code goes through the set of elements collected by the selector and then appends the button to every one of them.

Bringing in Another Dimension of Class

In addition, you can combine objects with jQuery to multiple elements. Suppose you have a pre-defined button element stored in a variable:

JavaScript

let buyButton = $('<button class="buy-now">Buy Now</button>');

$('.product').append(buyButton.clone());

Here:

  • We create a button element using $('<button class="buy-now">Buy Now</button>') and assign the value to the buyButton variable.
  • .clone() method duplicates the button element.
  • We place the cloned button into each element selected by $('.product').

This technique guarantees that every button that will be used with the appended button has its own unique element. This makes it possible to style or handle events independently if necessary.

Iterating with Loops: Efficiency will be a Key Aspect

When facing several elements, looping through them is more efficient. Here's how to rewrite the previous example using the .each() method:

JavaScript

$('.product').each(function(index, element) {

$(this).append('<button class="buy-now">Buy Now</button>');

});

In this code:

  • .each() goes through each element of $('.product') chosen.
  • The callback function receives two arguments:

index: The index of the current element in the selected range.

element: The actual DOM element.

  • The current element being processed is pointed by $(this) inside the loop.
  • We append the button element utilizing $(this).append("'<button class='buy-now'>Buy Now</button>'");

This method will accomplish the same purpose as those in the previous cases; however, it will have better readability and efficiency for longer selections.

Filtering Before Appending: Focusing on Certain Elements

Not all elements of a selection need to apply appending. jQuery's filtering methods, like .filter(), can be used to filter elements targeted before the appending of content.

For example, consider a product listing where only "featured" products should have a "Sale" badge appended:

JavaScript

$('.product').filter('.featured').append('<span class="sale">Sale!</span>');

Here:

  • $('.product').filter('.featured') will get all elements with the append class jQuery "product" and then filter the selection to only include elements with the class "featured" (which is maybe the class that identifies featured products).
  • .append('<span class="sale">Sale!</span>') is used to add a "Sale" badge to the featured product items that have been filtered.

It guarantees that the badge is just added to elements that have been "featured" marked.

Best Practices and Considerations: It Is Important to Make Your Code Clear and Concise

Although append() is a beneficial method for manipulating the DOM, you should be aware that keeping the code neat and readable is necessary, especially for bigger projects and collaboration. Here's why:

  1. Understanding Code at a Glance: The indentation only shows the nesting structure of your code, which is readable and makes it easier to see the flow and hierarchy of elements being appended. Let's suppose you are writing a grocery list and you don't indent the items; it would be difficult to separate fruits from vegetables and dairy products!
  2. Collaboration and Maintainability: When working with a team or revising your code yourself, clear indentations make grasping the logic of it more accessible to everyone. Visualize reading a six-line equation that is all on the same line. Without the proper formatting, the equation would be extremely difficult to read.
  3. Performance Conditions with DOM Manipulation: append() is an important tool that can be used in many situations, but the performance implications must be considered, especially when dealing with large data sets or frequent appends.
  4. Browser Rendering: Each time you use append(), the browser processes the DOM structure anew to reflect the changes. Too much information can slow down the page load and make the user feel sluggish. Think of a chef adding one ingredient after another to a pot while the guests are waiting to eat the food right away—it might take more time to cook it.
  5. Alternatives for Performance: In situations with large amounts of data or frequent changes, it is a good idea to use document fragments or virtual DOM libraries instead to achieve optimized rendering.

Wrapping Up

Implementing the recommended techniques and exploring other approaches, you are sure to succeed in creating dynamic and engaging web pages while keeping in mind code readability and performance. Take note! Practice does make a man perfect- try the jQuery append function in your projects to exploit its full potential.

FAQs

1. What is the purpose of the append() function in jQuery?

The append function in jQuery is applied to insert the content which is specified by the parameter to the end of each element of the matched set. It does that by creating the dynamic addition of HTML elements, text, or content to the DOM (Document Object Model) tree.

2. Which jQuery method is used to append a child element to a parent element?

The jQuery method of adding an element to another element is the `append()` method.

3. What is the main difference between append and appendChild?

- `append()` (jQuery): It is a jQuery function used to append content to the end of the selected elements.

- `appendChild()` (JavaScript): It is a JavaScript method that is responsible for adding a node as the last child of a node.

While there are some similarities between them, the `append()` method is jQuery-specific and has a simpler syntax for inserting content in DOM, while `appendChild()` is a native JavaScript method that is used to append DOM nodes.

4. How do you prepend an element before another element using jQuery?

You can use the `insertBefore()` method in jQuery to prepend an element to an existing element. For example:

JavaScript

$('#targetElement').insertBefore('#destinationElement');

This will insert `#targetElement` in front of `#destinationElement`.

5. Why do we use append?

We employ the `append()` function in jQuery to dynamically display content on our web pages, thus empowering them to become more dynamic and responsive. It facilitates developers in bringing changes to the DOM by adding more elements, text, HTML code, etc. when the user's action or any other event triggers it.

6. What is the function of append?

The `append()` function in jQuery plays a significant role in creating an engaging user experience and a dynamic website by adding content to the DOM on the fly. It is the core source of dynamic web applications where the content is added or updated based on the user's interactions or data changes.

image

mukesh

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...