Differences between. attr () and. data () in jQuery

Source: Internet
Author: User

Differences between. attr () and. data () in jQuery

$. Attr () and $. data () are essentially the Differences Between DOM attributes and Jquery object attributes.

Jquery object attributes and DOM attributes

A simple example

<! DOCTYPE html> 

• $. Attr () retrieves attribute values from the DOM element each time, that is, they are consistent with the attribute values in the labels in the view. • $. Attr ('data-foo') obtains the data-foo attribute value from the tag;

• $. Attr ('data-foo', 'World') inserts the 'World' string into the 'data-foo' attribute of the tag;

• $. Data () is a value from the Jquery object. Because the object property value is stored in the memory, it may be different from the attribute value in the view. • $. Data ('foo') obtains the foo attribute value from the Jquery object, instead of the data-foo attribute value from the label;

• $. Data ('foo', 'World') inserts the string 'World' into the 'foo' attribute of the Jquery object, rather than the data-foo attribute of the view tag.

Based on the above Code and explanations, you should be able to understand the differences between the two.

Summary

Therefore, $. attr () and $. data () should be used together to avoid the following two situations:

1. set attributes through $. attr () and get attribute values through $. data;

2. set attributes through $. data () and get attribute values through $. attr.

In terms of performance, we recommend that you use $. data () for set and get operations, because it only modifies the attribute value of the Jquey object and does not cause additional DOM operations.

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.