How to set and get HTML tag content using jQuery

We can use jQuery to set and get the content of HTML tags using methods like .html() and .text(). With html() function we can retrieve or set the HTML content (including inner HTML tags) of the selected HTML tag. With text() function we can retrieve or set the plain text content (without HTML tags) of the selected HTML tag. Example is mentioned below: text() & html() methods example


<html>
<head>
    <title>Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

    <div id="sourceElem">Source HTML Content</div>
    <div id="destinationElem"></div>

    <br>
    <button id="btnGetText">Get Text</button>
    <button id="btnSetText">Set Text</button>
    <button id="btnGetHTML">Get HTML</button>
    <button id="btnSetHTML">Set HTML</button>

    <script>
        $(document).ready(function () {
            $('#btnGetText').on('click', function () {
                alert($("#sourceElem").text());
            });

           $('#btnSetText').on('click', function () {
                $("#destinationElem").text($("#sourceElem").text());
            });

            $('#btnGetHTML').on('click', function () {
                alert($("#sourceElem").html());
            });
            
            $('#btnSetHTML').on('click', function () {
                $("#destinationElem").html($("#sourceElem").html());
            });
        });
    </script>
</body>
</html>