Insert content after element(s) in jQuery
In this tutorial, you will learn how to insert content after element(s) using jQuery.
Solution
To add HTML content after element(s) in the document using jQuery, you can use the after()
method. Call the after()
method on the element or elements, and pass the required HTML content string as argument.
element.after('some html content');
where you can replace the 'some html content'
with your required text or content.
Programs
1. In the following script, when user clicks on the button, we insert an image element after the first paragraph using after()
method.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#action").click(function() {
// Select the first paragraph
var element = $("p:first");
// Insert content after the first paragraph
element.after('<img src="/wp-content/uploads/2022/12/sample.png" alt="My image">');
});
});
</script>
</head>
<body>
<h2>Hello User!</h2>
<input type="submit" id="action" value="Click Me"></input>
<p>This is a paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
<p>This is fourth paragraph.</p>
<h2>Another section</h3>
<p>This is fifth paragraph.</p>
</body>
</html>