Cover Image for jQuery appendTo() method
81 views

jQuery appendTo() method

The jQuery appendTo() method is used to insert selected elements as children at the end (the last child) of another specified target element. It allows you to move elements from one location to another within the DOM.

The syntax for using the appendTo() method is as follows:

$(elementToBeAppended).appendTo(targetElement);
  • elementToBeAppended: It is a string or a jQuery object that represents the elements you want to append to the target element.
  • targetElement: It is a string, a DOM element, or a jQuery object representing the element where the selected elements will be appended.

Here’s an example of how you can use the appendTo() method:

HTML:

<div id="sourceDiv">
  <p>This is the content to be appended.</p>
</div>

<div id="targetDiv">
  <p>This is the existing content of the target div.</p>
</div>

JavaScript:

// Append the content from sourceDiv to targetDiv
$('#sourceDiv p').appendTo('#targetDiv');

After executing the above JavaScript code, the p element inside the sourceDiv will be moved and inserted at the end of the targetDiv:

Resulting HTML:

<div id="sourceDiv"></div>

<div id="targetDiv">
  <p>This is the existing content of the target div.</p>
  <p>This is the content to be appended.</p>
</div>

In the example, the appendTo() method is used to move the p element from sourceDiv and append it to the end of targetDiv. The p element is selected using the $('#sourceDiv p') selector, and it is then appended to the target element using appendTo('#targetDiv').

The appendTo() method is particularly useful when you want to move elements or blocks of content from one place to another within the DOM. It allows you to easily reorganize and modify the structure of your web page dynamically. It is a convenient way to manage the position and order of elements based on user interactions or other events.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS