jQuery html() Method

You are Here:

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

ValueExplanation
htmlStringSpecifies a string of HTML to set as the content of each matched element.
funcSpecifies a function returning the HTML content to set.

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>

Reminder

Hi Developers, we almost covered 99.5% of jQuery Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in jQuery.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author