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:

$(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:

$(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:

<!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>
Please follow and like us:
Content Protection by DMCA.com