jQuery html() Method

Last Updated:

jQuery html() Method

The jQuery html() method gets or sets the html content (innerHTML) of the selected elements.

Note: The following points to be considered when using the jQuery html() method

  • When this method is used to get content, it gets the html content of the first matched element.
  • When this method is used to set content, it will overwrite all matched elements.

In the following example, we will get the html content inside the <div> tag.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery html() Method</h1> <div> <p>Click on the button and check your console.</p> <button>Click Me</button> </div> <script> $(document).ready(function(){ $("button").click(function(){ console.log($("div").html()); }); }); </script> </body> </html>

Syntax

// Get content $(selector).html(); // Set content $(selector).html(htmlString); // Set content using a function $(selector).html(func)

Parameter Values

Value Explanation
htmlString Specifies a string of HTML to set as the content of each matched element.
func Specifies a function returning the HTML content to set.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
html()YesYesYesYesYesYesYesYesYesYesYesYesYes

Set HTML Content

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery html() Method</h1> <button>Click Me</button> <p></p> <script> $(document).ready(function(){ $("button").click(function(){ $("p").html("This is <strong>Paragraph</strong>"); }); }); </script> </body> </html>

Set HTML Content using Function

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery html() Method</h1> <button>Click Me</button> <p></p> <script> $(document).ready(function(){ $("button").click(function(){ $("p").html(function(){ var txt = "This is <strong>Paragraph</strong>"; return txt; }); }); }); </script> </body> </html>

Share this Page

Meet the Author