javascript tutorial - [Solved-5 Solutions] .prop() Vs .attr() - javascript - java script - javascript array


So jQuery 1.6 has the new function prop() .

    //instead of:
    //do we use:
click below button to copy the code. By JavaScript tutorial team
  • or in this case do they do the same thing?
  • And if we do have to switch to using prop(), all the old attr() calls will break if we switch to 1.6?


selector = '#id'

$(selector).click(function() {
    //instead of:
    var getAtt = this.getAttribute('style');
    //do we use:
    var thisProp = $(this).prop('style');
    var thisAttr = $(this).attr('style');

    console.log(getAtt, thisProp, thisAttr);
<script src=""></script>
<div id='id' style="color: red;background: orange;">test</div>
click below button to copy the code. By JavaScript tutorial team

The console logs the getAttribute as a string, and the attr as a string, but the prop as a CSSStyleDeclaration, Why? And how does that affect my coding in the future?

Solution 1:


  • My original answer applies specifically to jQuery 1.6. My advice remains the same but jQuery 1.6.1 changed things slightly: in the face of the predicted pile of broken websites, the jQuery team
  • We can see the difficulty they were in but still disagree with the recommendation to prefer attr().

Original answer

If you've only ever used jQuery and not the DOM directly, this could be a confusing change, although it is definitely an improvement conceptually. Not so good for the bazillions of sites using jQuery that will break as a result of this change though.

I'll summarize the main issues:

  • We usually want prop() rather than attr().
  • In the majority of cases, prop() does what attr() used to do. Replacing calls to attr()with prop() in our code will generally work.
  • Properties are generally simpler to deal with than attributes. An attribute value may only be a string whereas a property can be of any type. For example, the checked property is a Boolean, the style property is an object with individual properties for each style, the sizeproperty is a number.
  • Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as value and checked: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the defaultValue / defaultChecked property).
  • This change removes some of the layer of magic jQuery stuck in front of attributes and properties, meaning jQuery developers will have to learn a bit about the difference between properties and attributes. This is a good thing.
  • If you're a jQuery developer and are confused by this whole business about properties and attributes, we need to take a step back and learn a little about it, since jQuery is no longer trying so hard to shield we from this stuff. For the authoritative but somewhat dry word on the subject, there's the specs: DOM4 , HTML DOM , DOM Level 2 , DOM Level 3 . Mozilla's DOM documentation is valid for most modern browsers and is easier to read than the specs, so we may find their DOM reference helpful. There's a section on element properties.
  • As an example of how properties are simpler to deal with than attributes, consider a checkbox that is initially checked. Here are two possible pieces of valid HTML to do this:
<input id="cb" type="checkbox" checked>
<input id="cb" type="checkbox" checked="checked">
click below button to copy the code. By JavaScript tutorial team

So, how do we find out if the checkbox is checked with jQuery?

  • <input id="cb" type="checkbox" checked>
  • <input id="cb" type="checkbox" checked="checked">
  • This is actually the simplest thing in the world to do with the checked Boolean property, which has existed and worked flawlessly in every major scriptable browser since 1995:
  • if (document.getElementById("cb").checked) {...}
  • The property also makes checking or unchecking the checkbox trivial:

document.getElementById("cb").checked = false

In jQuery 1.6, this unambiguously becomes

$("#cb").prop("checked", false)

The idea of using the checked attribute for scripting a checkbox is unhelpful and unnecessary. The property is what we need.

  • It's not obvious what the correct way to check or uncheck the checkbox is using the checkedattribute
  • The attribute value reflects the default rather than the current visible state (except in some older versions of IE, thus making things still harder). The attribute tells we nothing about the whether the checkbox on the page is checked.

Solution 2:

  • A DOM element is an object, a thing in memory. Like most objects in OOP, it has properties. It also, separately, has a map of the attributes defined on the element (usually coming from the markup that the browser read to create the element). Some of the element's properties get their initialvalues from attributes with the same or similar names (value gets its initial value from the "value" attribute; href gets its initial value from the "href" attribute, but it's not exactly the same value; className from the "class" attribute). Other properties get their initial values in other ways: For instance, the parentNode property gets its value based on what its parent element is; an element always has a style property, whether it has a "style" attribute or not.
  • Let's consider this anchor in a page
<a href='foo.html' class='test one' name='fooAnchor' id='fooAnchor'>Hi</a>
click below button to copy the code. By JavaScript tutorial team

Some gratuitous ASCIWE art (and leaving out a lot of stuff):

href:       "" 
name:       "fooAnchor"                   
 id:         "fooAnchor"                 

className:  "test one"                   
href:  "foo.html"                    
name:  "fooAnchor"                    
id:    "fooAnchor"                  
class: "test one"                   
click below button to copy the code. By JavaScript tutorial team
  • Note that the properties and attributes are distinct.
  • Now, although they are distinct, because all of this evolved rather than being designed from the ground up, a number of properties write back to the attribute they derived from if we set them. But not all do, and as we can see from href above, the mapping is not always a straight "pass the value on", sometimes there's interpretation involved.
  • When we talk about properties being properties of an object, I'm not speaking in the abstract. Here's some non-jQuery code:
var link = document.getElementById('fooAnchor');
alert(link.href);                 // alerts ""
alert(link.getAttribute("href")); // alerts "foo.html"
click below button to copy the code. By JavaScript tutorial team
  • The link object is a real thing, and we can see there's a real distinction between accessing a property on it, and accessing an attribute.
  • As Tim said, the vast majority of the time, we want to be working with properties. Partially that's because their values (even their names) tend to be more consistent across browsers. We mostly only want to work with attributes when there is no property related to it (custom attributes), or when we know that for that particular attribute, the attribute and the property are not 1:1 (as with hrefand "href" above).
  • The standard properties are laid out in the various DOM specs:

These specs have excellent indexes and we recommend keeping links to them handy; we use them all the time.

  • Custom attributes would include, for instance, any data-xyz attributes we might put on elements to provide meta-data to our code (now that that's valid as of HTML5, as long as we stick to the data- prefix). (Recent versions of jQuery give we access to data-xyz elements via the datafunction, but that function is not just an accessor for data-xyz attributes [it does both more and less than that]; unless we actually need its features, I'd use the attr function to interact with data-xyz attribute.)
  • The attr function used to have some convoluted logic around getting what they thought we wanted, rather than literally getting the attribute. It conflated the concepts. Moving to prop and attr was meant to de-conflate them. Briefly in v1.6.0 jQuery went too far in that regard, but functionality was quickly added back to attr to handle the common situations where people use attr when technically they should use prop.

Solution 3:


  • HTML: &textarea id="test" value="foo">
  • JavaScript: alert($('#test').attr('value'));
  • In earlier versions of jQuery, this returns an empty string. In 1.6, it returns the proper value, foo.
  • Without having glanced at the new code for either function, WE can say with confidence that the confusion has more to do with the difference between HTML attributes and DOM properties, than with the code itself. Hopefully, this cleared some things up for you.

Solution 4:

  • A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.
  • If we change an attribute, the change will be reflected in the DOM (sometimes with a different name).
  • Example: Changing the class attribute of a tag will change the className property of that tag in the DOM. If we have no attribute on a tag, we still have the corresponding DOM property with an empty or a default value.
  • Example: While our tag has no class attribute, the DOM property className does exist with a empty string value.
  • If we change the one, the other will be changed by a controller, and vice versa. This controller is not in jQuery, but in the browser's native code.

Solution 5:


  • Use prop() over attr() in the majority of cases.
  • A property is the current state of the input element. An attribute is the default value.
  • A property can contain things of different types. An attribute can only contain strings

Related Searches to javascript tutorial - .prop() Vs .attr()