Skip to content

jQuery insert into div

  • by

To insert content into a <div> element using jQuery, you can use the .html() method or the .append() method. Here’s an example of both approaches:

$(document).ready(function() {
  // Select the target <div> element using its ID or any other suitable selector
  var divElement = $('#your-div-id');

  // Insert content using the .html() method
  divElement.html('<p>This is the inserted content.</p>');
});

Using the .append() method:

$(document).ready(function() {
  // Select the target <div> element using its ID or any other suitable selector
  var divElement = $('#your-div-id');

  // Append content using the .append() method
  divElement.append('<p>This is the appended content.</p>');
});

These methods allow you to insert HTML content into the selected <div> element.

Remember to include the jQuery library in your HTML document before using jQuery code. You can do so by including the following script tag in the HTML’s <head> or <body> section:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

jQuery insert into div example

Simple example code that demonstrates both approaches using the .html() method and the .append() method to insert content into a <div> element using jQuery:

<!DOCTYPE html>
<html>
<head>
  <title>jQuery Insert into Div</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      // Select the target <div> element using its ID or any other suitable selector
      var divElement = $('#your-div-id');

      // Using the .html() method to replace the content
      divElement.html('<p>This is the replaced content.</p>');

      // Using the .append() method to add content
      divElement.append('<p>This is the appended content.</p>');
    });
  </script>
</head>
<body>
  <div id="your-div-id">
    <!-- The initial content of the div -->
  </div>
</body>
</html>

Output:

jQuery insert into div

When you open this HTML file in a web browser, you will see both the replaced content and the appended content within the <div> element.

Do comment if you have any doubts or suggestions on this jquery code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading