English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
jQuery html() method
Use the html() methodThe html() method gets or sets the content (innerHTML) of the selected element.GetWhen setting the content of the first selected element, it will returncontent.
Use the html() methodSetWhen setting content, it will overrideContent of all selected elements.
Note:When using html() to set the content of an element, all content in the element will be completely replaced by the new content. Additionally, before replacing the child elements with the new content, jQuery removes other constructs from the child elements, such as data and event handlers.
Usetext()The method only gets or sets the text content of the selected element.
Get content:
$(selector).html()
Set content:
$(selector).html(content)
Use a function to set the content:
$(selector).html(function(index, currentContent))
Click the button to get the content of the first paragraph:
$("button").click(function(){ alert($("p").html()); });Test to see‹/›
Clicking each paragraph will return the HTML content:
$("p").click(function(){ alert($(this).html()); });Test to see‹/›
Change the content of all paragraphs:
$("button").click(function(){ $("p").html("I want to say: <b>Hello world</b>); });Test to see‹/›
Use a function to change the content of an element:
$("button").click(function(){ $("p").html(function(i){ return "The index of this p element: " + i; }); });Test to see‹/›
The difference between html() method and text() method:
$("#btn1").click(function(){ $("p").html("I want to say: <b>Hello world</b>); }); $("#btn2").click(function(){ $("p").text("I want to say: <b>Hello world</b>); });Test to see‹/›
Parameter | Description |
---|---|
content | Set the HTML string content for all selected elements Note:If this parameter is omitted, html() will return the content of the first selected element |
function(index, currentContent) | Specify a function that returns the HTML content to be set
|