jQuery attr vs prop?

Unfortunately none of your links work 🙁

Some insight though, attr is for all attributes. prop is for properties.

In older jQuery versions (<1.6), we just had attr. To get to DOM properties such as nodeName, selectedIndex, or defaultValue you had to do something like:

var elem = $("#foo")[0];
if ( elem ) {
  index = elem.selectedIndex;
}

That sucked, so prop was added:

index = $("#foo").prop("selectedIndex");

This was great, but annoyingly this wasn’t backward compatible, as:

<input type="checkbox" checked>

has no attribute of checked, but it does have a property called checked.

So, in the final build of 1.6, attr does also do prop so that things didn’t break. Some people wanted this to be a clean break, but I think that the right decision was made as things didn’t break all over the place!

Regarding:

Prop: The value in it’s current state after any modifications via JavaScript

Attr: The value as it was defined in the html on page load.

This isn’t always true, as many times the attribute is actually changed, but for properties such as checked, there isn’t an attribute to change, so you need to use prop.

References:

http://blog.jquery.com/2011/05/03/jquery-16-released/

http://ejohn.org/blog/jquery-16-and-attr

Leave a Comment