.attr() and the addition of the .prop()/.removeProp() methods.attr(), .val(), and Event triggering.attr() method...<input class="foo"> // attribute
$('input')[0].className // property
<input id="bar"> // attribute
$('#bar')[0].id // property
Attributes are in the html, parsed by the browser to form the DOM, and (generally) correspond to properties.
These don't make sense in the world of attributes.
$(window).attr...
$(document).attr...
$("input").attr("selectedIndex");
$("#foo").attr("nodeType");
$("#bar").attr("tagName");
$("<input>").attr("type");
The spark of discussion, these are special. According to the spec, attributes such as checked do not map to properties of the same name.
The most common boolean attributes are checked, selected, readonly, and disabled<input type="checkbox" checked="checked"> // Maps to .defaultChecked (initial value)
$('input').attr('checked', true);
// Didn't set the checked property in 1.6
// Do this instead
$('input').prop('checked', true);
$('input').prop('checked', false);
example === truejQuery is not being used to set the checkbox here. This is to show that the native behavior of a checkbox as it is changed by the user does not keep the attribute up to date with the current value, just the property.
.attr() changes the property (still better to use .prop()).attr() can be used on the window/document (just defers to .prop()).attr(), but can now be retrieved with .prop().To retrieve and set the current value of an input,
you need the value property
$input.prop('value'); // Current value
$input[0].getAttribute('value'); // Default value
$input.attr('value');
// Right now, retrieves the property, but this will be deprecated in 1.7.
$input.val(); // Hey, there's a whole method devoted to value!
Use the.attr()method for attributes and the.prop()method for properties. Often, they will be the same value, but if you want any current values, meaning if it can change with user interaction, useprop. In cases where it doesn't make a difference,propwill be faster.
.attr() for attributes and .prop() for properties