Difference: 1. When the html() method obtains and sets the element, the html code is set. When the text() method obtains and sets the element, the element text content is set; 2. In the html() method The use of xml is not supported, but html and xml are supported in the text() method.
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
This method is similar to the innerHTML attribute in JavaScript. Can be used to read or set the HTML content in a certain element
In order to display the effect more clearly, change the HTML code of the
element to:
<p><strong>你最喜欢的男孩子是?</strong></p><p></p>
Then use the html() method to
element to obtain:
var p_html = $("p").html(); //获取<p>元素中的HTML代码alert(p_html); //打印</p><p>元素的HTML代码</p>
After running the code, the effect diagram is as follows:
Get the HTML code of the entire p element
If you need to set the HTML code of an element, you can also use this method, but you need to pass a parameter to it. For example, to set the HTML code of the
element, you can use the following code:
$("p").html("<strong>你最喜欢的男孩子是?</strong>"); //设置<p>元素的HTML代码</p>
Note: The html() method can be used for XHTML documents, but not for XML documents.
This method is similar to the innerText property in JavaScript and can be used to read and set the text in an element. content.
Continue to use the above HTML code:
<p><strong>你最喜欢的男孩子是?</strong></p>
Use the text() method to obtain the
element:
var p_text = $("p").text(); //获取<p>元素的文本内容alert(p_text); //打印</p><p>元素的文本内容</p>
After running the code, the effect diagram is as follows:
Only displays text content, does not include and display html code
Same as the html() method, if you need to set text content for an element, you also need to pass it a parameter. For example, to set the text content of the
element, the code is as follows:
$("p").text("你最喜欢的男孩子是?"); //设置<p>元素的文本内容</p>
Note: (1) The innerText attribute in JavaScript cannot run under some versions of Firefox browser, and jQuery The text() method supports all browsers.
(2) The text() method is valid for both HTML documents and XML documents.
Summary:
1. When the html() method gets and sets the element, it sets the HTML code
2. When the text() method gets and sets the element, it sets the The text content of the element
3. The html() method does not support xml, and the text() method supports html and xml
Recommended related video tutorials: jQuery video Tutorial
The above is the detailed content of What is the difference between text and html in jquery. For more information, please follow other related articles on the PHP Chinese website!