How to set HTML content of an element using jQuery?

To set the HTML content of an element, use the html() method. This method allows you to replace the existing HTML content inside a selected element with new HTML markup.

Syntax

The basic syntax for setting HTML content is −

$(selector).html(content)

Where content is the HTML string you want to insert into the element.

Example

You can try to run the following code to set HTML content of an element using jQuery −

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#button1").click(function(){
                $("#demo").html("<strong>This text is highlighted.</strong>");
            });
        });
    </script>
</head>
<body>
    <p id="demo">This is a paragraph.</p>
    <button id="button1">Click to set HTML</button>
</body>
</html>

In this example, when you click the button, the original paragraph text "This is a paragraph." will be replaced with the HTML content containing a <strong> tag, making the text bold.

Multiple Elements Example

You can also set HTML content for multiple elements at once −

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#button2").click(function(){
                $(".content").html("<em>Updated content with emphasis</em>");
            });
        });
    </script>
</head>
<body>
    <div class="content">First div content</div>
    <div class="content">Second div content</div>
    <button id="button2">Update All</button>
</body>
</html>

The html() method is powerful for dynamically updating page content and works with any valid HTML markup including tags, attributes, and nested elements.

Updated on: 2026-03-13T20:38:18+05:30

850 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements