jQuery Append/Prepend

The jQuery append() and prepend() methods allow you to dynamically insert content into selected elements. These methods are useful for adding elements at the beginning or end of another element's content.

Key Topics

Using append()

The append() method inserts content at the end of the selected elements.

$("#list").append("<li>New Item</li>");

Explanation: This code appends a new <li> element to the list with the ID list.

Using prepend()

The prepend() method inserts content at the beginning of the selected elements.

$("#list").prepend("<li>First Item</li>");

Explanation: This code prepends a new <li> element to the list with the ID list, making it the first item.

Example: Append and Prepend


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Append/Prepend Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <ul id="list">
        <li>Existing Item 1</li>
        <li>Existing Item 2</li>
    </ul>
    <button id="appendButton">Add to End</button>
    <button id="prependButton">Add to Beginning</button>

    <script>
        $(document).ready(function() {
            $("#appendButton").click(function() {
                $("#list").append("<li>New Item</li>");
            });

            $("#prependButton").click(function() {
                $("#list").prepend("<li>First Item</li>");
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example demonstrates how to use append() to add items to the end of a list and prepend() to add items to the beginning of the list dynamically.

Key Takeaways

  • Dynamic Content: Use append() to add elements to the end and prepend() to add elements to the beginning of another element's content.
  • Efficient DOM Manipulation: These methods simplify dynamically updating lists, tables, or other structures.
  • Interactive Applications: Combine these methods with event listeners for responsive UIs.