jQuery.attr() Vs. jQuery.prop() methods Difference

This article describes the distinction between the prop and attr methods in jQuery.

jQuery.Prop() Method

The jQuery prop() is an abbreviation for property.

This method returns the property value for the first element in the set of matched elements.

Syntax: - $(selector).prop(property)

It also returns the updated values of elements that have been modified using JavaScript/jQuery using the prop() method .

Take a look at this:

<a href='page.html' class='link_classes' name='linkName' id='linkID'>Hi</a>

$('#linkID').prop('href'); // returns "http://example.com/page.html"
$('#linkID').prop('name'); // returns "linkName"
$('#linkID').prop('id'); // returns "linkID"
$('#linkID').prop('className'); // returns "link classes"

jQuery.attr() Method

The attribute is known as jQuery attr().

This method is used to either get the value of an attribute from the first matched element or to set attribute values on all matched elements.

On page load, it returns the element’s value as defined in the html.

Attributes carry additional information about an HTML element and come in name=”value” pairs. You can set an attribute for HTML element and define it while writing the source code.

An attribute may only be of the string type, and this method returns the element’s default value.

Syntax : - $(selector).attr(attribute)

Example of the difference between jQuery.attr() and jQuery.prop()

The jQuery prop() returns a Boolean value for selected, checked, read-only, disabled, and so on, whereas attr() returns a string.

<input id="checkID" checked="checked" type="checkbox" />

$('#checkID').attr('checked') //returns checked
$('#checkID').prop('checked') //returns true

Both attr() and prop() are used to retrieve or update the value of a given property of an element attribute, although attr() returns the property’s default value (Original state), and prop() delivers the current value (Current state).

If an element has a default value, even if the value has changed, the attribute displays the default value.

<input type="text" name="username" value="user123">

$('input').prop('value', '456user');
$('input').prop('value'); // returns "456user"
$('input').attr('value'); // returns "user123"

When you want to set a custom attribute and there is no property associated, attributes can be useful.

<input type="text">

$('input').attr('customAttribute', 'something custom');
$('input').attr('customAttribute'); // returns "something custom"
$('input').prop('customAttribute'); // returns undefined

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories