jquery attr() vs prop() (difference)

according to the docs

jQuery.attr()
Get the value of an attribute for the first element in the set of matched elements.

whereas,

 jQuery.prop()
Get the value of a property for the first element in the set of matched elements.

Before jQuery 1.6 , the attr() method sometimes took property values into account when retrieving some attributes, which caused in inconsistent behavior. And thus, the prop() method was introduced. As of jQuery 1.6. , the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

What actually is Attributes?
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.

simple example can be:
    
here, "type","value", "id" are attributes of the input elements.

What is Property?
Property is a representation of an attribute in the HTML DOM tree. once the browser parse your HTML code ,corresponding DOM node will be created which is an object thus having properties.
in above case ,once browser renders the input, other properties like align, alt, autofocus, baseURI, checked so on will be added ...

since, attr() gives you the value of element as it was defines in the html on page load. It is always recommended to use prop() to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element's current state.

try it in fiddle

some other links to read more about attr() and prop().
Link 1
Link 2

Comments

  1. Very interesting article I Lear something I didn't new.

    ReplyDelete
  2. Great article by Jquery expert. I want to make your temple in my home Please!!!!

    ReplyDelete
  3. 1) The jQuery prop() grabs the specified DOM property whereas attr() grabs the specified HTML attribute.
    2) The jQuery prop() method returns boolean value for selected, checked, readOnly, disabled and so on while attr() returns a defined string.

    For details information look here:
    http://www.namasteui.com/difference-between-prop-and-attr/

    ReplyDelete
  4. Excellent blog!. I was looking for html tutorials and I landed your website through google search. I found your blog very interesting.

    ReplyDelete
  5. Great answer.Couldn't find elsewhere such a simple and understanding explanation.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Very Interesting information shared than other blogs
    Thanks for Sharing and Keep updating us

    ReplyDelete
  8. Nice Information can this can be integrated with other resources in extending their services.microsoft dynamics crm course

    ReplyDelete

Post a Comment

Popular posts from this blog

jQuery popup (dialog) form validation on a normal button click

Jquery :contains and making it Case-Insensitive