How to add new elements to DOM in jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery append() or prepend() method

You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements whereas the prepend() method insert content to the beginning of matched elements.

The following example will show you how to add new items to the end of an ordered list using the jQuery append() method.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Add Elements to DOM</title>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         $("button").click(function(){
  •             $("ol").append("<li>list item</li>"); 
  •         });
  •     });
  • </script>
  • </head>
  • <body>
  •     <button>Add new list item</button>
  •     <ol>
  •         <li>list item</li>
  •         <li>list item</li>
  •         <li>list item</li>
  •     </ol>
  • </body> 
  • </html>

Similarly you can add elements to the beginning of matched elements.

The following example will show you how to add heading to the beginning of an paragraph using the jQuery prepend() method.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Add Elements to DOM</title>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         $("button").click(function(){
  •             $("p").prepend("<h1>This is a heading</h1>"); 
  •         });
  •     });
  • </script>
  • </head>
  • <body>
  •     <p>This is a paragraph.</p>
  •     <button>Add heading</button>
  • </body> 
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.