← Previous Next →


jQuery html() method is used to change the entire content of the selected elements. It replaces the selected element content with new contents.

Note: It is a very useful function but works in a limited area because of its API documentation. The API documentation of the jQuery html function consists of three method signatures.

The first method signature has no argument, so it just returns the HTML within that element. The remaining two signatures take a single argument: i.e. a string or a function that returns a string.

Syntax:

$(selector).html()  

It is used to return content.

$(selector).html(content)  

It is used to set content.

$(selector).html(function (index, currentcontent)) 

It is used to set content by calling function.

The jQuery html() method is used either for set the content or return the content of the selected elements.

  • To set content: When you use this method to set content, it overwrites the content of the all matched elements.
  • To return content: When you use this method to return content, it returns the content of the first matched element.

The text() method is used to set or return only the text content of the selected elements.

Parameters of jQuery html() method

Parameter  Description
Content  It is an essential parameter. It is used to specify the new content for the selected elements. It can also contain HTML tags.
Function (index, currentcontent)

It is an optional parameter. It specifies a function that returns the new content for the selected elements.

Index: It shows the index position of the element in the set.
Currentcontent: It shows the current HTML content of the selected element.

 

Example of jQuery html() method

Let's take an example to demonstrate jQuery html() method. It is changing the content of all p elements.

<!DOCTYPE html>  
        <html>  
        <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").html("Hello <b>
Javatpoint.com</b>
"); }); }); </script> </head> <body> <button>
Click here to change the content of all p elements</button> <p>
This is a paragraph.</p> <p>
This is another paragraph.</p> </body> </html>
← Previous Next →