Analysis of differences between attr and prop in jquery

  • 2020-05-17 04:44:36
  • OfStack

When should prop be used after the prop method is introduced in the higher version of jquery? When do you use attr? What's the difference between the two? These problems arise.

There are many answers online about the difference between the two. Here's what I learned. My lesson is simple:
The & # 8226; The prop method is used when dealing with attributes inherent to the HTML element itself.
The & # 8226; We use the attr method for our own custom DOM attributes for the HTML element.

The above description may be a little vague, but just a few examples.


<a href="http://www.baidu.com" target="_self" class="btn"> baidu </a>

In this case < a > The DOM attributes of the element are "href, target, and class" < a > The attributes that the element itself carries are also included in the W3C standard, or properties that can be intelligently suggested in IDE. These are called intrinsic attributes. When working with these properties, the prop method is recommended.


<a href="#" id="link1" action="delete"> delete </a>

In this case < a > The DOM attributes of the element are "href, id and action". Obviously, the first two are inherent attributes, while the last one is "action". < a > The element itself does not have this attribute. This is the custom DOM property. When working with these properties, the attr method is recommended. The undefined value is returned when the prop method is used to evaluate and set the property value.

Here's another example:


<input id="chk1" type="checkbox" /> Whether or not visible <input id="chk2" type="checkbox" checked="checked" /> Whether or not visible

For elements like checkbox, radio and select, the selected attributes correspond to "checked" and "selected". These are also inherent attributes, so you need to use the prop method to get the correct results.


$("#chk1").prop("checked") == false $("#chk2").prop("checked") == true

If the attr method is used above, it will appear:


$("#chk1").attr("checked") == undefined
$("#chk2").attr("checked") == "checked"

The full text.

That's all for this article, I hope you enjoy it.


Related articles: