jQuery Add Elements with Examples


To add elements in jQuery, let us see two methods: jQuery after() method

The after() method in jQuery is used to insert specified content after the selected elements.

Example

Let us now see an example to implement the jQuery after() method −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("#btndemo").click(function(){
         $("img").after("<strong>Text inserted after!</strong>");
      });
   });
</script>
</head>
<body>
<img src="https://www.tutorialspoint.com/images/tp-logo-diamond.png" alt="Tutorialspoint Logo" width="220" height="120"><br><br>
<button id="btndemo">Insert specified content</button>
</body>
</html>

Output

This will produce the following output −

Click on the above button to display the text −

jQuery before() method

The before() method in jQuery is used to insert specified content before the selected elements.

Let us now see an example to implement the before() method in jQuery −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("#btndemo").click(function(){
         $("img").before("<strong>Text inserted before!</strong>");
      });
   });
</script>
</head>
<body>
<img src="https://www.tutorialspoint.com/images/tp-logo-diamond.png" alt="Tutorialspoint Logo" width="220" height="120"><br><br>
<button id="btndemo">Insert specified content</button>
</body>
</html>

Output

This will produce the following output −

Click on “Insert specified content” −

Updated on: 11-Nov-2019

47 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements