jQuery appendTo()

The jQuery appendTo() method is used to insert content at the end of the selected elements, the same as that of the jQuery append() method. The only difference is in the syntax and placement of the content and target in these two methods.

In the append() method, the selected element is treated as a target and the content to be inserted is treated as an argument of the append() method.

Syntax:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$(selector).append(content)
$(selector).append(content)
$(selector).append(content)

In the appendTo() method, the content to be inserted is the selected element, and the target is treated as an argument of the appendTo() method.

Syntax:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$(content).appendTo(selector)
$(content).appendTo(selector)
$(content).appendTo(selector)

Content:

  • Content is a compulsory parameter of the jQuery appendTo() method, as it specifies the content to insert at the end of the selected element.
  • It can accept the following values: HTML elements, jQuery objects, and DOM elements.

Selector:

  • It is also a mandatory parameter, as it specifies the place where the content needs to be inserted.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("<span>How are you?</span>").appendTo("p");
});
});
</script>
</head>
<body>
<button>Click me</button>
<p>Hello! </p>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("<span>How are you?</span>").appendTo("p"); }); }); </script> </head> <body> <button>Click me</button> <p>Hello! </p> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("<span>How are you?</span>").appendTo("p");
});
});
</script>
</head>
<body>
<button>Click me</button>
<p>Hello! </p>
</body>
</html>