jQuery: .attr() vs .prop()

In jQuery, both .prop() and .attr() methods are used to manipulate properties and attributes of HTML elements, but they serve different purposes and have some important distinctions:

.prop() Method

  1. The .prop() method is primarily used for getting or setting properties of DOM elements, such as boolean attributes (e.g., checked, disabled) or properties (e.g., selectedIndex, nodeName).
  2. It is recommended for working with properties that represent the current state of an element, especially when dealing with form elements and their states (checked, selected, disabled).
  3. When used with properties, it typically returns the current state as a boolean value (true or false) or sets the state by passing true or false as an argument.

.attr() Method

  1. The .attr() method is used for getting or setting attributes of HTML elements, such as standard HTML attributes (e.g., src, href, class) or custom attributes.
  2. It is suitable for working with attributes that are part of the element's initial state and remain constant throughout the element's lifecycle.
  3. When used with attributes, it usually returns the current attribute value or sets a new value for the attribute.

Working with Checked State (Property) vs. Data Attribute (Attribute)

<input type="checkbox" id="myCheckbox" checked="checked" data-info="Some data" /> // Using .prop() to get/set the checked state (property) var isChecked = $("#myCheckbox").prop("checked"); // Returns true $("#myCheckbox").prop("checked", false); // Unchecks the checkbox // Using .attr() to get/set the data attribute var info = $("#myCheckbox").attr("data-info"); // Returns "Some data" $("#myCheckbox").attr("data-info", "New data"); // Updates the data attribute

In this example, .prop() is used for the checked state property, and .attr() is used for the data attribute.

Working with Standard Attributes

<a href="https://www.example.com" id="myLink">Visit Example</a> // Using .attr() to get/set the href attribute var linkHref = $("#myLink").attr("href"); // Returns "https://www.example.com" $("#myLink").attr("href", "https://www.newlink.com"); // Updates the href attribute

In this case, .attr() is used to work with the standard HTML href attribute.

Conclusion

The choice between .prop() and .attr() depends on whether you are dealing with properties that represent the current state of elements (use .prop()) or attributes that define the element's initial characteristics (use .attr()). Understanding this difference is crucial for proper manipulation of elements in jQuery.