Possible Duplicate:
.prop() vs .attr()
Given the new .prop()
method in jQuery, which is the preferred way to create a new element with particular fields, e.g. a link:
$('<a>').prop('href', '...');
$('<a>').attr('href', '...');
$('<a href="...">');
I've always tended to use #2, but it's unclear whether a new element being put in the DOM shouldn't now use #1 instead.
prop() method provides a way to explicitly retrieve property values, while . attr() retrieves attributes. For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the . prop() method.
Difference between .prop() and attr() method are:This method returns the current value. This method returns the default value. This method is mainly used when the user wants to change the value for an HTML tag's attribute. This method is mainly used to set the default value for an HTML tag's attribute.
jQuery deprecated (version 1.6) and removed (version 1.9) the use of . attr() for use to set "checked" and "disabled" properties. It also points out that attempting to retrieve values by using . attr() will result in confusion/problems, as in this example: $elem.
The prop() method sets or returns properties and values of the selected elements. When this method is used to return the property value, it returns the value of the FIRST matched element. When this method is used to set property values, it sets one or more property/value pairs for the set of matched elements.
I would go with attr()
in that case. You're creating a new <a>
element and setting its href
HTML attribute, so it would make sense to emphasize that.
However, since the href
attribute directly maps to the href
DOM property, using prop()
would have the exact same result.
Let's take another example, more relevant to the differences between attr()
and prop()
: suppose you want to set the class
attribute of the <a>
element instead of its href
. The sample code in your question becomes:
$('<a>').prop('className', '...');
$('<a>').attr('class', '...');
$('<a class="...">');
IMHO, (2) and (3) make one's intent clearer than (1). The fact that there cannot be a DOM property named class
, because that token might be a reserved word in the host language, is at best an implementation detail. The class
HTML attribute is usually what we're thinking about in that context.
Of course, there are situations where the opposite is true, e.g. when working with "boolean" HTML attributes like checked
or disabled
. In that case, it would be more robust to set the strongly-typed DOM property instead of creating the less well-defined HTML attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With