Jquery HTML() vs InnerHTML()?



What is the difference between html() and innerhtml() function in jquery???



Suppose you have HTML like this:

<div class="mydiv">
This is a test
<div>

Now, to change the content within div class "mydiv", you would use jquery html(). As an example, if I want to change the inner output to "Hello World" like this:

<div class="mydiv">
Hello World
<div>

I would use the following jquery html() api:

$('.mydiv').html("Hello World");

Jquery html() api can also be used to fetch the html content as follows:

var mycontent = $('.mydiv').html();

This is equivalent to the following javascript innerhtml() code:

var mycontent = document.getElementById('mydiv').innerhtml();

Thus with jquery html() you can fetch html within a div element and update div elements. With innerhtml() you can fetch html in a div element. In this case, both html() and innerhtml() are equivalent. Jquery html() function makes use of innerhtml() api for its function.

jQuery's .html() function is used to read and modify the html contents of a page

Jquery .text() is used to change the text content in contrast to complete html() (that includes all div, span etc) within the div.

.innerhtml() is being used by .html() function to do its operation.

Jquery .html() does some checks on nodeType and then calls innerhtml(). It also does exception handling in a try/catch block where it trys to use innerHTML first and if that fails, it fallbacks gracefully to jQuery .empty() + append().

Unfortunately, Innerhtml() has poor support in IE and also has inconsistent behavior in different browsers.