Skip to content

jQuery attr & prop

11 May 2011

Reasonable though, the differentiation between properties and attributed in jQuery 1.6 caused some problems with existing code so a new version (1.6.1) release candidate is on the way.

Along with some bugs fixed attributes are updated to remove confusion. Boolean attributes will work again as they used to work so

$(“:checkbox”).attr(“checked”, true);

is now acceptable again. But some, as window and document’s, won’t work because neither window nor document object have attributes but properties. So if window.location should be get or set manipulation must be made by .prop() method. In jQuery 1.6.1, the .attr() will defer to the .prop() method for both the window and document instead of throwing an error.

Now boolean attributes (such as checked) will set the default or initial value (i.e. whether a checkbox will be checked when the page loads). Properties in turn will keep the current values.

So $(“:checkbox”).get(0).checked = true; is the same as  $(":checkbox:first").prop(“checked”, true); and $(“:checkbox”).attr(“checked”, true); won’t check the checkbox in version 1.6.

In the interest of backwards compatibility the .attr() method,  will continue to be able to get and set these boolean attributes in jQuery 1.6.1.

List of boolean attributes/properties that jQuery 1.6.1 supports dynamically getting and setting with .attr() includes:

autofocus, autoplay, async, checked, controls, defer, disabled,
hidden, loop, multiple, open, readonly, required, scoped, selected

.prop() is recommended for setting these attributes/properties, but old code will continue working in jQuery 1.6.1.

Neither .attr() nor .prop() is intended for getting/setting value. .val() method should be used (although using .attr(“value”, “somevalue”) will continue to work, as it did before 1.6).


From → jQuery

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: