The jQuery appendTo() method inserts the specified html elements at the end of the selected elements.
Syntax of jQuery appendTo() Method
$(content).appendTo(selector)
content: This is the mandatory parameter. This contains HTML elements that are inserted at the end of selected elements by appendTo() method. This content must always have html tags.
Important Note: If content field contains already existing html elements then those elements will be moved from the current position to the end of the selected elements.
selector: This is also a mandatory parameter. This selects the elements after which the specified content is inserted.
jQuery appendTo() method Example
In the following example, we have a H1 heading as an html element and two paragraphs. We are appending the H1 tag at the end of each paragraph using appendTo() method. Since H1 is already present in the html page, it will be moved from its current position and appended at the end of each p element as shown in the output screenshot.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1").appendTo("p");
});
});
</script>
</head>
<body>
<h1>jQuery appendTo() Example</h1>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<button>Move and append H1 heading at the end of paragraphs</button>
</body>
</html>
Output:
Before button click:
After button click:
Leave a Reply