Cover Image for jQuery after() method
112 views

jQuery after() method

In jQuery, the after() method is used to insert content after each of the selected elements. It allows you to add new elements or text after the target elements, making them siblings to the selected elements.

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

To insert HTML content:

$(targetElement).after(content);

To insert DOM elements or jQuery objects:

$(targetElement).after(element1, element2, ...);
  • targetElement: It is a string or a jQuery object that represents the elements after which you want to insert the content.
  • content: It can be an HTML string, a DOM element, a jQuery object, or text that you want to insert after the target elements.

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

HTML:

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

JavaScript:

// Insert a new paragraph element after the target div
$('#targetDiv').after('<p>After the target div.</p>');

After executing the above JavaScript code, a new p element will be inserted after the targetDiv:

Resulting HTML:

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

You can also use after() to insert existing DOM elements or jQuery objects:

// Create a new paragraph element
var newParagraph = $('<p>After the target div.</p>');

// Insert the new paragraph element after the target div
$('#targetDiv').after(newParagraph);

In this example, we first create a new p element using jQuery and then use after() to insert it after the targetDiv.

The after() method is useful when you want to dynamically add content after elements, such as inserting new elements or text as siblings to existing elements. It is commonly used in combination with other jQuery methods and event handlers to create interactive and dynamic web pages.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS