Attribute vs Property

What’s the difference between an “attribute” and a “property”?

As usual, let’s start smaller.

What is a property?
JS DOM objects have properties. These properties are kind of like instance variables for the particular element. As such, a property can be different types (boolean, string, etc.). Properties can be accessed using jQuery’s prop method (as seen below) and also by interacting with the object in vanilla JS.

Let’s take a look:

As you can see, all of the properties we set in the HTML are available through prop. Other properties are available too, such as style, even though we didn’t explicitly set them.

Properties can also be updated through the prop method:

What is an attribute?
Attributes are in the HTML itself, rather than in the DOM. They are very similar to properties, but not quite as good. When a property is available it’s recommended that you work with properties rather than attributes.

An attribute is only ever a string, no other type.

If an element has a default value, the attribute shows the default value even if the value has changed.

Attributes can be useful when you want to set a custom attribute, that is, when there is no property associated.

But, to be fair, you can also use custom properties (although this might be bad practice).

Points to Remember:

  1. selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected..etc should be retrieved and set with the .prop() method. These do not have corresponding attributes and are only properties.
  2. for a checkbox (jquery 1.6+)

    prop method returns Boolean value for checked, selected, disabled, readOnly..etc while attr returns defined string. So, you can directly use .prop(‘checked’) in if condition.
  3. .attr() calls .prop() internally so .attr() method will be slightly slower than accessing them directly through .prop().

For jQuery 1.6+, prop will be mostly used because it is simple and wider than attr. In most old projects, attr is used to get current state information of element. But now prop has taken this job and attr would be replaced with prop.