The attr() function in jQuery is used to get or set the value of an attribute. As an example, this line will return the value of href for the first a in the set:
// returns the href of the first a in the document $('a').attr('href');
When setting an attribute with attr() all elements in the set will be affected.
// sets the href for all a elements in the document $('a').attr('href', 'http://example.com');
HTML elements can have attributes and properties. A good example to understand the difference between an attribute and a property is the checked attribute of a checkbox. If the checked attribute is set in HTML a checkbox will be initially checked.
<input type="checkbox" checked>
Here it gets interesting: If the checkbox is clicked, the attribute does not change. The value returned by attr(‘checked’) will always be ‘checked’, no matter how often the checkbox is clicked. But the identically named property does change.
// returns the current state of a checkbox (true/false) $(elem).prop('checked');
The above line will always return the actual state of a checkbox. It will return true if checked and false if not checked.
The attribute should be used only to set the initial value of the checkbox. Although it’s technically possible to alter the state of the checkbox by setting/unsetting the attribute, it is not good practice.
// use prop('name', value) to check or uncheck a checkbox dynamically $(elem).prop('checked', true);
The same is true for other attributes like selected, value and disabled.