How to insert an element into DOM using jQuery?


There may be a situation when you would like to insert new one or more DOM elements in your existing document. jQuery provides various methods to insert elements at various locations.

The after( content ) method insert content after each of the matched elements whereas the method before( content ) method inserts content before each of the matched elements.

After content

The after( content ) method inserts content after each of the matched elements.

Example

You can try to run the following code to learn how to insert an element into DOM, with after() method:

Live Demo

<html>

   <head>
      <title>jQuery after(content) method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).after('<div class = "div"></div>' );
            });
         });
      </script>
       
      <style>
         .div {
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
      </style>
   </head>
   <body>
   
      <p>Click on any square below to see the result:</p>
       
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>
</html>

Before content

The before( content ) method inserts content before each of the matched elements.

Example

You can try to run the following code to learn how to insert an element into DOM, with before() method:

Live Demo

<html>

   <head>
      <title>jQuery before(content) method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).before('<div class = "div"></div>' );
            });
         });
      </script>
       
      <style>
         .div {
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below to see the result:</p>
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>
</html>

Updated on: 17-Dec-2019

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements