JavaScript - - By Craig Buckler

jQuery 1.6.1 Released: .attr() Backward-Compatibility Fix

Version 1.6 of jQuery was released two weeks ago. One of the primary changes was the separate handling of DOM Attributes and Properties. In essence, consider:


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

In earlier versions of jQuery, $("#i").attr("checked") would return true. However, in v1.6, the same code would return an empty string ("") since that was the actual value of the HTML “checked” attribute when the page was loaded. The value of the DOM property would be retrieved using $("#i").prop("checked") — which would return true.

Unfortunately, this change caused a little confusion within the community and could break scripts. The main problem is that an empty string is falsy so, although it’s the correct value, it introduces boolean logic flaws which could be awkward to debug:


if ($("#i").attr("checked")) {
	// this code runs in previous versions of jQuery
}
else {
	// this code runs in jQuery 1.6
}

The jQuery team try to maintain compatibility with older releases. For this reason, the v1.6.1 .attr() method reverts to its original functionality and the code above will evaluate to ‘true’.

The documentation has also been clarified with respect to HTML boolean attributes such as ‘checked’:

  • The .prop() method should be used for boolean attributes/properties and for properties which do not exist in HTML.
  • Boolean attributes which can be seen in the HTML should continue to be manipulated with the .attr() method.

The HTML boolean attributes are: autofocus, autoplay, async, checked, controls, defer, disabled, hidden, loop, multiple, open, readonly, required, scoped, and selected.

It’s great that the jQuery team listen to their users and are willing to overrule a logical development decision for the sake of stability and backward compatibility. Perhaps other project teams could learn from their example?

jQuery 1.6.1 also fixes around 20 minor bugs and can be downloaded from:

http://code.jquery.com/jquery-1.6.1.js
http://code.jquery.com/jquery-1.6.1.min.js

Was your code affected by the jQuery v1.6 .attr() change?

Sponsors