html method in jQuery with examples


1. html() method gets the html content of first element from the set of matched elements.
2. We can manipulate the html content using this method.
3. This method uses the browser's innerHTML property.
4. While returning, it returns html content of first element from set of matched elemets, but while setting it sets html content for all the elements matching the selector.


Example 1 : Returning HTML

        <html>
        <head>
        <title>HTML</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#NameButton").click(function () {
                    var text = $(".para").html();
                    alert(text);
                });
            });
        </script>
        </head>
        <body>
        <p class="para">This is html in jquery</p>
        <p class="para">Hello World !!</p>
        <input type ="button" id="NameButton" value="click" />
        </body>
        </html>
    
Demo :




In the above example, we have rendered a paragraph element with some text. On click of button we are reading its html content and showing it using alert.
    We have two paragraph elements having same class attribute. In jQuery we are selecting elements using class selector. As mentioned earlier html method reads content or html of first element from set of matched elements, it returns the html of first paragraph element.



Example 2 : Setting HTML



        <html>
        <head>
        <title>HTML</title>
        <style>
        #myDiv
        {
        background-color:gray;
        margin-left:400px;
        width:200px;
        height:200px;
        font-family:comic sans ms;
        }
        </style>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#myDiv").hover(function () {
                    $(this).html("Mouse pointer entered the div. This text will disappear as you move out of the div.");
                }, function () {
                    $(this).html('');
                });
            });
        </script>
        </head>
        <body>
        <div id="myDiv">
        </div>
        </div>
        </body>
        </html>
    
Demo :




In above example, we have used combination of hover event and html method. On hovering the div, we are setting the html content of the div using html method.
   On un hovering the div the html content is set back to empty.


1 comments: