menu

Friday, November 21, 2014

Using html() and innerHTML in JQuery

html() vs innerHTML:

     You can either use html() function to set or get value of a div using JQuery objects like $("#myDiv").html() or use innerHTML property of the html dom object like 
$("#myDiv")[0].innerHTML. You see that a JQuery object is hold an array of html dom objects of the same name. Below is an example of using these syntax.

Example:

<html>
 <head>
  <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
  <script>
    $(document).ready(function() {
      $('#myButton').click(function () { 
  $('#myDiv').html('test');
      alert("Jquery object value " + $('#myDiv').html());
      alert("HTML Dom object value " + $('#myDiv')[0].innerHTML);
       return true;
      });   
     });
  </script>
 </head>
 <body>
   <input type="button" id="myButton" value="fill the div">
   <br/>
   <div id="myDiv"></div>
  </body>
</html>     

The screen will look like the following.


Using html() and innerHTML in JQuery
Figure 1

You can download the source code from here.

No comments:

Post a Comment