jQuery html() example

The html() method sets or returns the content (innerHTML) of the selected elements.

Syntax

This method does not accept any arguments:
$(selector).html()
Set the HTML contents of each element in the set of matched elements:
$(selector).html(content)
Set content using a function:
$(selector).html(function(index,currentcontent))

Example 1 - Get the HTML Contents

Click a paragraph to convert it from HTML to text.
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>html demo</title>
    <style>
        p {
            margin: 8px;
            font-size: 20px;
            color: blue;
            cursor: pointer;
        }

        b {
            text-decoration: underline;
        }

        button {
            cursor: pointer;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <p>
        <b>Click</b> to change the <span id="tag">html</span>
    </p>
    <p>
        to a <span id="text">text</span> node.
    </p>
    <p>
        This <button name="nada">button</button> does nothing.
    </p>

    <script>
        $("p").click(function() {
            var htmlString = $(this).html();
            $(this).text(htmlString);
        });
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

Example 2 - Set the HTML Contents

Add some html to each div.
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>html demo</title>
    <style>
        .red {
            color: red;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <span>Hello</span>
    <div></div>
    <div></div>
    <div></div>

    <script>
        $("div").html("<span class='red'>Hello <b>Again</b></span>");
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

References

Comments