jQuery .html() gets and sets HTML

Description

.html() gets or sets a value depending on whether you feed it an argument.

.text() works with both XML and HTML documents, .html() doesn't. .text() gets the text contents of all descendants, whereas .html() retrieves only the first element matched.

Syntax for .html() (getter)

.html()

gets the HTML contents of the first element in the set of matched elements.

Its return value is a string containing the HTML representation of the element.

Syntax for .html() (setter)

  • .html(htmlString)
    htmlString: A string of HTML to set as the content of each matched element
  • .html(function)
    function: A function returning the HTML content to set

Its return value is the jQuery object, for chaining purposes.

Set and get HTML content

The following example both gets and sets HTML content of a div tag:


<!DOCTYPE html>
<html>
    <head>
        <script src="http://java2s.com/style/jquery-1.8.0.min.js">
        </script>
        <script>
            $(function(){<!--  ww w.ja  v a2  s.c  om-->
                var content = $("div").html();
                document.writeln(content);
                $("div").html("<p style='color:red;'>RED</p>");
            });
        </script>
    </head>
    <body>
        <div>
            <ul>
            </ul>
        </div>
    </body>
</html>

Click to view the demo

Both .text() and .html() also accept a function as a parameter for setting content.

Use function to create content dynamically

This allows for dynamic creation of content, instead of just static text.


<!DOCTYPE html>
<html>
    <head>
        <script src="http://java2s.com/style/jquery-1.8.0.min.js">
        </script>
        <script>
            $(function(){<!-- w  ww . j  a va 2  s . c o m-->
                $("div#testHTML").html(function(){
                    var content = "";
                    for(i = 1; i <=3; i++){
                        content += "testing " + i + "...<br />";
                    }
                    return content;
                });
            });
        </script>
    </head>
    <body>
        <div id="testHTML">
        </div>
    </body>
</html>

Click to view the demo

Set paragraph content and apply style

The following code sets content for a paragraph and then set color value for <p>.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from www  .  j  a  v a2s . co m-->
               $("p").html("<b>bold</b>");
               $("p b").append(document.createTextNode("added")).css("color", "red");
        });
    </script>
  </head>
  <body>
    <body>
         <p>java2s.com</p>

  </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities