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
Release: 2024-11-28 13:00:12
Original
474 people have browsed it

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");
Copy after login

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");
Copy after login

Example:

To clarify the process, consider the following demonstration:

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

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

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

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template