How to Create a DIV Element in jQuery

Topic: JavaScript / jQueryPrev|Next

Answer: Use the jQuery append() Method

You can simply use the append() method to create an element such as a <div> at the end of the selected element in jQuery. Similarly, you can use the prepend() to create or insert element at the beginning. Take a look at the following example to see how this works:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>Create HTML Elements Using jQuery</title>
  • <style>
  •     .container{
  •         padding: 20px;
  •         background: #f2f2f2;
  •         border: 5px solid #aaa;
  •     }
  •     .content{
  •         padding: 10px;
  •         border: 3px solid orange;
  •     }
  • </style>
  • <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  • <script>
  • $(document).ready(function(){
  •     // Insert elements on click of the button
  •     $("button").click(function(){
  •         // Creating a div element at the end
  •         $(".container").append('<div class="content">Appended DIV</div>');   
  •         // Creating a div element at the start
  •         $(".container").prepend('<div class="content">Prepended DIV</div>'); 
  •     });    
  • });
  • </script>
  • </head>
  • <body>
  •     <div class="container">
  •         <h1>This is a heading</h1>
  •         <p>This is a paragraph.</p>
  •         <p><button type="button">Insert DIV</button></p>
  •     </div>
  • </body>
  • </html>

jQuery also provide methods, like before() and after() to create the elements before or after the selected elements. See the tutorial on jQuery insert content to learn more about it.

Related FAQ

Here are some more FAQ related to this topic:

Your Feedback:

We would love to hear from you, please drop us a line.