The difference between html-and-text methods in jquery

Source: Internet
Author: User

Usually when writing Ajax with jquery, the HTML () method is used instead of the text (), what is the difference between them?

First,there are two methods in the HTML attribute, one with a parameter and one without a parameter.

1. No parameter HTML (): Gets the HTML content of the first matching element. This function cannot be used with XML documents. But it can be used in an XHTML document, which returns a string

Example:

HTML page Code:<div><span>hello</span></div>

jquery Code: $ ("div"). html ();

Result:<span>hello</span>

2. Parameter HTML (val): Sets the HTML content for each matching element. This function cannot be used with XML documents. But it can be used in XHTML documents. Returns a JQuery object

HTML page Code:<div></div>

jquery Code: $ ("div"). html ("<p>nice to meet you</p>");

Results:<div><p> Nice to meet you</p></div> (HTML tags will be recognized by the browser)

Second,there are two methods in the Text property, one with a parameter, one without a parameter

1. No parameter text (): Gets the contents of all matching elements. The result is text that is combined with the text content contained by all matching elements. The return is a string.

Example:

HTML page Code:<p><span>hello<span><div> fine</div></p>

jquery Code: $ ("P"). text ();

Result: Hello fine

2. Parameter text (val): Sets the text content of all matching elements, similar to HTML (), but encodes the HTML (replaces "<" and ">" with the corresponding HTML entity). Returns a JQuery object.

HTML page Code:<div>paragraph.</div>

jquery Code: $ ("div"). Text ("<b>Some</b> new text.");

Result: <p><b>Some</b> new text.</p> (HTML tags are not recognized by the browser, but are output as strings)

From the example above, we know that the difference between the HTML () method and the text () method is that it differs in the recognition of HTML tags.

The difference between html-and-text methods in jquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.