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:
- 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).
- 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).
- 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.
- 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.
- It is suitable for working with attributes that are part of the element's initial state and remain constant throughout the element's lifecycle.
- 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)
In this example, .prop() is used for the checked state property, and .attr() is used for the data attribute.
Working with Standard Attributes
In this case, .attr() is used to work with the standard HTML href attribute.
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.