jQuery HTML Method

jQuery provide 3 methods to set or Get the content from a DOM element i.e. text() , html() and val() . jQuery html() method get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element. Also, by using HTML() with a jQuery object you can replace the contents of any container element like the < div > or < p >, < span > and others. When this method is used to set content, it overwrites the content of ALL matched elements. It is important to note that This method uses the browser's innerHTML property . Some browsers may not return HTML that exactly replicates the HTML source in an original document. Syntax
$(selector).html()

Get HTML Contents with html() Method

$("#btnIn").click(function(){ var str = $("#innerDiv").html(); alert(str); });
$("#btnOut").click(function(){ var str = $("#outerDiv").html(); alert(str); });
<div id="outerDiv"> Outer Div <div id = "innerDiv">Inner Div</div> </div>
run this source code Browser View


Outer Div
Inner Div
Full Source
<html> <head> <title>jQuery html() example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#btnIn").click(function(){ var str = $("#innerDiv").html(); alert(str); }); $("#btnOut").click(function(){ var str = $("#outerDiv").html(); alert(str); }); }); </script> </head> <body> <button id="btnIn">Get InnerDiv HTML</button> <button id="btnOut">Get OuterDiv HTML</button> <div id="outerDiv" style="border: 2px solid red;width:260px;"> Outer Div <div id = "innerDiv" style="border: 2px solid green; width:150px;">Inner Div</div> </div> </body> </html>

Set HTML Contents with html() Method

$("#btnSet").click(function(){ $("body").html("<Div>New Div!!!!</Div>"); });
run this source code Browser View
Outer Div
Inner Div
Full Source
<html> <head> <title>jQuery html() method example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $(".btnSet").click(function(){ $(".innerDiv").html("<div>New Div added!!!!</div>"); }); }); </script> </head> <body> <button class="btnSet">Set HTML</button> <div class="outerDiv"> Outer Div <div class = "innerDiv">Inner Div</div> </div> </body> </html>

Difference between jQuery: text() and html() ?

  1. .text() can be used in both XML and HTML documents.
  2. .html() is only for html documents.