jQuery html() method is used to set or return the content of the selected elements.
When html() method is used to set the content of the selected elements, it overwrites the content of all the matched selected elements. For example, the code $("p").html("BeginnersBook");
will change the content of all the paragraphs to “BeginnersBook”.
When html() method is used to return the content of the selected elements, it returns the content of the first matched element and ignores the rest. For example, if there are multiple paragraphs on a page then the code $("p").html()
would return the content of first paragraph only.
jQuery html() Syntax
To return the content:
$(selector).html()
To set the content:
$(selector).html(content)
jQuery html() Example to set element content
In the following example, on the button click event we are changing the content of all the paragraphs using html() method. See the screenshots in the output.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").html("Hi <b>Friends</b>"); }); }); </script> </head> <body> <h2>jQuery html() example on Beginnersbook.com</h2> <p>Welcome to Beginnersbook.com</p> <p>This is my second paragraph</p> <button>Set Content</button> </body> </html>
Output:
Before the button is clicked:
This screenshot is taken when the page is initially loaded and we have not yet clicked the button.
After the button is clicked:
This screenshot is taken after we have clicked the button. As you can see, the content of all the paragraphs is changed.
jQuery html() Example to return element content
In the following example we are using html() method to get the content of selected element. When we get the content using html() method, it returns the content of only first matched element. This is the reason, in the following example, only the content of first paragraph is displayed in the alert message.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ alert($("p").html()); }); }); </script> </head> <body> <h2>jQuery html() example on Beginnersbook.com</h2> <p>Welcome to <b>Beginnersbook.com</b></p> <p>This is my <b>second</b> paragraph</p> <button>Get Content</button> </body> </html>
Output:
Before the button is clicked:
This screenshot is taken when the page is initially loaded and we have not yet clicked the button.
After the button is clicked:
This screenshot is taken after we have clicked the button. As you can see, the content of the first paragraph is displayed in the alert message.
Leave a Reply