jQuery is a JavaScript library that simplifies DOM manipulation and event handling. To dynamically add elements to a web page using jQuery, you can use the following methods:
Method 1 : append() and appendTo() methods
append()
method appends content to the end of the selected elements.appendTo()
method appends selected elements to the end of the target element. <div id="container"> <!-- Existing content --> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function() { // Creating a new element var newElement = $("<p>New element added!</p>"); // Appending the new element to the container newElement.appendTo("#container"); }); </script> |
Method 2 : prepend() and prependTo() methods:
prepend()
method inserts content at the beginning of the selected elements.prependTo()
method inserts selected elements at the beginning of the target element. <div id="container"> <!-- Existing content --> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function() { // Creating a new element var newElement = $("<p>New element added!</p>"); // Prepending the new element to the container newElement.prependTo("#container"); }); </script> |
Method 3 : after() and insertAfter() methods:
after()
method inserts content after the selected elements.insertAfter()
method inserts selected elements after the target element.<div id="existingElement"> <!-- Existing content --> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function() { // Creating a new element var newElement = $("<p>New element added!</p>"); // Inserting the new element after the existing element newElement.insertAfter("#existingElement"); }); </script> |
Method 4 : before() and insertBefore() methods:
before()
method inserts content before the selected elements.insertBefore()
method inserts selected elements before the target element.<div id="existingElement"> <!-- Existing content --> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function() { // Creating a new element var newElement = $("<p>New element added!</p>"); // Inserting the new element before the existing element newElement.insertBefore("#existingElement"); }); </script> |