Difference between Attr and Prop in jQuery

Many developers confused with the Attr and Prop keyword in jQuery. So We are describing here the difference between Attr and Prop in jQuery.

jQuery.attr()
Gets the value of an attribute for the set of matched elements.

Whereas:
jQuery. Prop ()
Gets the value of a property for the set of matched elements.

The segregation of attr() and prop() should help alleviate some of the confusion between HTML attributes and DOM properties. $.fn.prop() grabs the specified DOM property, while $.fn.attr() grabs the specified HTML attribute.

Difference between HTML attributes and DOM properties:

Attributes carry additional information about an HTML element and come in name=”value” pairs. You can set an attribute for a HTML element and define it when writing the source code.

For example:

In above given example, “id”, “type” and “value” are attributes of the input elements.

Property

Property is a representation of an attribute in the HTML DOM tree. Once the browser parses the HTML code, the corresponding DOM node will be created that is an object thus having properties.

Since attr() gives you the value of an element as it was defined in the HTML on page load. It is always recommended to use prop() to get the values of elements modified via JavaScript/jQuery in the browser at rumtime. It always keeps the current state value.

The property always represents the current state while the attribute (except in old versions of IE) represents the initial state or is meant for HTML attributes since they are strictly defined. The attribute tells you nothing about the current state.

The Prop() method returns a Boolean value for checked, selected, disabled, readOnly and so on while attr returns a defined string. So, we can directly use .prop(“checked”) in an if condition.

.attr() calls .prop() internally so the .attr() method will be slightly slower than accessing them directly through .prop().

You Might Interested In

1 COMMENT

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.