jQuery interview question · Most asked

What is the difference between .attr() and .prop()?

Summary

.attr() reads and writes HTML attributes (the markup); .prop() reads and writes DOM properties (the live state of the element). For state such as checked, selected, disabled and value, use .prop(): the attribute holds the initial value, while the property reflects what the user did.

Longer Answer

$("#agree").attr("checked") may return "checked" or undefined based on the original markup even after the user unticks the box; $("#agree").prop("checked") returns the current boolean. Use .attr() for things like href, data-* (or .data()), aria-* and custom attributes. This distinction was introduced in jQuery 1.6 and is a common source of bugs in older code.

Key Points

  • attr = HTML attribute; prop = live DOM property.
  • Use prop for checked/selected/disabled.
  • attr for href, aria-*, custom attributes.

More most-asked jQuery questions

← All jQuery questions