Jquery appendTo And prependTo Example

In this article, we will see jquery appendTo() and prependTo() examples. The prependTo() method inserts HTML elements at the beginning of the selected elements. The appendTo() method inserts HTML elements at the end of the selected elements. The .append() and .appendTo() methods perform the same task. The major difference is in the syntax.

The .append() method selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup and it is inserted into the target container.

The .prepend() method selector expression preceding the method is the container into which the content is inserted. With .prependTo(), on the other hand, the content precedes the method, either as a selector expression or as markup. and it is inserted into the target container.

Example: appendTo() Method

Syntax:

$(content).appendTo(selector);

In this example, Insert the span element at the end of each P tag when clicking on the button.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("<span> Hello, Techsolutionstuff !!</span>").appendTo("p");
  });
});
</script>
</head>
<body>

<h3>Jquery appendTo and prependTo Example - Techsolutionstuff</h3>

<p>This is a paragraph.</p>

<button>Insert span element at the end of each P tag</button>

</body>
</html>

Output: 

jquery_append_to_example

 

 

Example: prependTo() Method

Syntax:

$(content).prependTo(selector);

In this example, Insert the span element at the beginning of the P tag when clicking on the button.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("<span>Hello, Techsolutionstuff !! </span>").prependTo("p");
  });
});
</script>
</head>
<body>

<h3>Jquery appendTo and prependTo Example - Techsolutionstuff</h3>

<p>This is a paragraph.</p>

<button>Insert span element at the beginning of P tag</button>

</body>
</html>

Output:

jquery_prepend_to_example


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS