• jQuery Video Tutorials

jQuery appendTo() Method



The appendTo() method in jQuery is used to append HTML elements at the end of the set of matched elements. This method accepts a parameter named "selector", which specifies the target element(s) to which the content will be appended at the end.

If we want to append the HTML elements at the beginning of the selected target elements, we need to use the prependTo() method.

Syntax

Following is the syntax of appendTo() method in jQuery −

$(content).appendTo(selector)

Parameters

This method accepts the following parameters −

  • content: The HTML elements to be appended at the end of the target element(s).
  • selector: The target element(s) to which the content will be appended.

Note: If the content provided is already an existing element, it will be moved from its current position in the DOM and then inserted at the end of chosen target element(s).

Example 1

In the following example, we are using the appendTo() method to append a <span> element at the end of the <p> element −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("<span><i> This is a newly appended span element.</i></span>").appendTo("p");
  })
});
</script>
</head>
<body>
<p>Paragraph element.</p>
<button>Click here!</button>
</body>
</html>

After executing and clicking the button, the <span> element will be appended at the end of <p> element.

Example 4

In the below example, we are appending an existing element (<span>) at the end of the paragraph element −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("span").appendTo("p");
  })
});
</script>
</head>
<body>
<span><i> This is a newly appended span element.</i></span>
<p>Paragrapah element.</p>
<button>Click here!</button>
</body>
</html>

As the provided content is already an existing element, it will be moved from its current position in the DOM and then inserted after the <p> (target element).

jquery_ref_html.htm
Advertisements