Cover Image for jQuery insertAfter() method
107 views

jQuery insertAfter() method

The jQuery insertAfter() method is used to insert the selected elements after the specified target element in the DOM. It allows you to move elements from one location to another within the DOM.

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

$(elementsToBeInserted).insertAfter(targetElement);
  • elementsToBeInserted: It is a string or a jQuery object that represents the elements you want to insert after the target element.
  • targetElement: It is a string, a DOM element, or a jQuery object representing the element after which the selected elements will be inserted.

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

HTML:

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

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

JavaScript:

// Insert the content from sourceDiv after targetDiv
$('#sourceDiv p').insertAfter('#targetDiv');

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

Resulting HTML:

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

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

<p>This is the content to be inserted.</p>

In the example, the insertAfter() method is used to move the p element from sourceDiv and insert it after targetDiv. The p element is selected using the $('#sourceDiv p') selector, and it is then inserted after the target element using insertAfter('#targetDiv').

The insertAfter() 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