jquery
  1. jquery-html

JQuery html()

The .html() method in jQuery is used to get or set the HTML content of the selected element.

Syntax

To get the HTML content of an element:

$(selector).html();

To set the HTML content of an element:

$(selector).html(htmlString);

Use

The .html() method is useful for manipulating the content of an element. It can be used to get the current HTML content of an element, or to set new HTML content to the element.

Example

Here is an example of using the .html() method to change the content of an element:

HTML:

<div id="myDiv">
    <p>Hello, world!</p>
</div>

JavaScript:

$(document).ready(function(){
    $("#myDiv").html("<p>Goodbye, world!</p>");
});

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery AJAX POST Example</title>
    <!-- Include jQuery library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<div id="myDiv">
    <p>Hello, world!</p>
</div>

    <script>
  $(document).ready(function(){
    $("#myDiv").html("<p>Goodbye, world!</p>");
});
    </script>
</body>
</html>
Try Playground

In this example, we use the .html() method to set the content of the #myDiv element to <p>Goodbye, world!</p>.

Summary

The .html() method in jQuery is a powerful tool for manipulating the content of an element. It can be used to get or set the HTML content of an element, making it easy to modify the content of your page dynamically. Try it out in your next jQuery project!

Published on: