jQuery Html Function Example

Let's have a closer look at the jQuery .html() function.

Demo Code Download

Description

Using .html() is the most common way to get or set the content of an element using jQuery. If you just want the text and not HTML tags you can simply use .text() which will return a string containing the combined text of all matched elements. These functions are browser dependant (ie - .html() uses the browser's innerHTML property) so the results returned(white space, new lines etc) will depend on the browser you are using. In this example we also make use of the .empty() function which is a quick way to get rid of the content within and .prev() which can be used to reference the preceding element, in this case this is the demo buttons. Lets have a look at an example of the html jQuery function in action. Further Reading »

Demo

jQuery Function Demo - jQuery4u.com

Demo: Getting the content of an element.

Run Demo View Code


Download

The download package includes all the inline HTML, CSS, JavaScript, jQuery and images required for the .html() function demo so you can try it yourself and change as you please.

The full code listing for all jQuery functions have been now added to GitHub, you can get them there, we are making them work with the latest versions of jQuery!

Code

<!-- Copyright 2011 jQuery4u.com -->
<!DOCTYPE html>
<html>
<title>jQuery Function Demo - jQuery4u.com</title>
<head>
    <script src="http://www.jquery4u.com/function-demos/js/jquery-1.6.4.min.js"></script>
    <script src="http://www.jquery4u.com/scripts/function-demos-script.js"></script>

    <script type="text/javascript">

    var JQFUNCS =
    {
        runFunc:
        {
            /* ------------------------------ html Demo ------------------------------ */
            "html":
            {
                run: function(id)
                {
                    var demobox = $('#'+id);
                    demobox.empty();
                    demobox.append(demobox.prev().html()+'<br/>');
                    demobox.append(demobox.prev().text()+'<br/>');
                },

                reset: function(id)
                {
                    $('#'+id).hide();
                }
            }
        }
    }

    </script>

</head>
<body>

<p class="example">Demo: Getting the content of an element.</p>
<p><a href="#" id="html-demobtn" class="demobtn btn actionr">Run Demo</a> <a href="#" id="html-codebtn" class="codebtn btn actionr">View Code</a> <a href="#" id="html-resetbtn" class="resetbtn btn actionr" style="display: none;">Reset</a></p>
<div class="demoarea" id="html" style="border:1px solid orange; padding:20px;"></div>

</body>
</html>
<!-- Copyright 2011 jQuery4u.com -->