jquery
  1. jquery-appendto

jQuery appendTo()

jQuery appendTo() is a method that allows the user to append an element to another element. It is a simple and efficient way to manipulate the DOM (Document Object Model) and can be used to dynamically add content to a webpage.

Syntax

The syntax for jQuery appendTo() is as follows:

$(selector).appendTo(target)

Where selector is the element to be moved, and target is the element to which it will be appended.

Use

The appendTo() method is used to insert HTML content at the end of a selected element. It is especially useful for dynamic web pages where new content needs to be added dynamically and in real-time without refreshing the page.

Example

Suppose we want to move a list item from one list to another list when a button is clicked. We can achieve that using the following code:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery appendTo() Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("#list1 li:last").appendTo("#list2");
            });
        });
    </script>
</head>
<body>

<h2>jQuery appendTo() Example</h2>

<ul id="list1">
    <li>List Item 1</li>
    <li>List Item 2</li>
    <li>List Item 3</li>
</ul>

<button>Move Last Item to List 2</button>

<ul id="list2">
    <li>List Item A</li>
    <li>List Item B</li>
</ul>

</body>
</html>
Try Playground

In this example, we have two lists: list1 and list2. When the button is clicked, the last item from list1 is moved to list2. We achieve that using the appendTo() method.

Summary

jQuery appendTo() is an essential method for manipulating the DOM in real-time and adding new content to a webpage. It is particularly useful for dynamic web pages that require frequent updates in real-time. With its simple syntax and efficient functionality, jQuery appendTo() is an essential tool for developers working on modern web pages and applications.

Published on: