Home >Web Front-end >JS Tutorial >How Can I Append or Prepend a DIV Element Using jQuery?

How Can I Append or Prepend a DIV Element Using jQuery?

DDD
DDDOriginal
2024-11-28 13:00:12482browse

How Can I Append or Prepend a DIV Element Using jQuery?

Moving Elements: Appending and Prepending

Consider the need to relocate a DIV element, including its children, from one location ("source") to another ("destination"). The desired outcome is to have the source content nested within the destination container.

Solution:

AppendTo Method:

This method moves the source element to the end of the destination element, becoming its final child:

$("#source").appendTo("#destination");

PrependTo Method:

Alternatively, the prependTo method inserts the source element at the beginning of the destination element, making it the first child:

$("#source").prependTo("#destination");

Example:

To clarify the process, consider the following demonstration:

$("#appendTo").click(function() {
  $("#moveMeIntoMain").appendTo($("#main"));
});

$("#prependTo").click(function() {
  $("#moveMeIntoMain").prependTo($("#main"));
});
#main {
  border: 2px solid blue;
  min-height: 100px;
}

.moveMeIntoMain {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>

The above is the detailed content of How Can I Append or Prepend a DIV Element Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn