Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between prop() and attr() in jQuery and when to use attr() and prop() [duplicate]

Tags:

jquery

attr

prop

I saw in some places .attr() is used in jQuery.In some places .prop() is used.But i searched in SO and google i am very confused .Please tell me the exact difference between these two and when to use them.

I have seen the following links jQuery attr vs. prop, there are a list of props? jQuery attr vs prop?

But I did not got the answer.Please help me.Thanks in advance.

Before giving a downvote please explain the reason, then I will correct in my next post.

like image 670
PSR Avatar asked Apr 17 '13 04:04

PSR


People also ask

Should I use ATTR or prop?

Since attr() gives you the value of an element as it was defined in the HTML on page load. It is always recommended to use prop() to get the values of elements modified via JavaScript/jQuery in the browser at rumtime. It always keeps the current state value.

What is the purpose of attr () function in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

Is ATTR deprecated in jQuery?

attr() deprecated/removed for use with "checked" and "disabled" properties. Many sites now use various means to update their version of jQuery to a later version than 1.4, the version in Drupal 7. jQuery deprecated (version 1.6) and removed (version 1.9) the use of .


1 Answers

from docs

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

example

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

updated after comment

You can set an attribute for HTML element. You define it while writing the source code, once the browser parse your code, corresponding DOM node will be created which is an object thus having properties.

Simple example can be..

<input type="test" value="test" id="test" /> 

Here type, value, id are attributes.Once browser renders it, you will get other properties like align, alt, autofocus, baseURI, checked and so on.

link if you want to read more on this

like image 60
bipen Avatar answered Nov 09 '22 07:11

bipen