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
- How do you make AJAX requests with jQuery?
- What is the difference between .html() and .text(), and why does it matter for security?
- What is event delegation, and why is it useful?
- What is the difference between $(document).ready(), $(fn), DOMContentLoaded and window.onload?
- How do you bind and unbind events in modern jQuery? What happened to bind, live and delegate?
- What are jQuery Deferreds, and how do you wait for several requests?
- What is the difference between preventDefault(), stopPropagation() and returning false in a jQuery handler?
- What is jQuery, and is it still relevant today?