Skip to content

jQuery – DOM Attributes and Properties

10 May 2011

jQuery 1.6 introduces .prop() and .removeProp() methods which allow modifying or removing a DOM property.

.prop()

method get a property value of the first found element and returns it as a string. If required property has not been set or searched element has not been found returned values will be undefined .

Earlier jQuery versions used to get the value of a property or attribute the .attr() method. Version 1.6 differentiate both attributes and properties supplying method for each of them. For instance .attr(“checked”) of an input type=”checkbox” element will return “checked” or empty string (“”) rather than true/false (as is the case is previous versions).

The preferred way to determine if a checkbox is checked (in cross-browser-compatible way) one of the following might be used:

  • if ( elem.checked )
  • if ( $(elem).prop("checked") )
  • if ( $(elem).is(":checked") )

.attr(“checked”) will retrieve the attribute, which does not change but stores the default or initial value of the checked property. Here is a short snippet demonstrating this behavior:

<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>

<script>
$("input").change(function() {
  var $input = $(this);
  $("p").html(".attr('checked'): <b>" + $input.attr('checked') + "</b><br>"
              + ".prop('checked'): <b>" + $input.prop('checked') + "</b><br>"
              + ".is(':checked'): <b>" + $input.is(':checked') ) + "</b>";
}).change();
</script>

.prop() accept an string input parameter identifying property to get. In this case method returns a string representing property value.

As a second parameter a value (or function returning desired value) to set is applicable. If function is used within it, the keyword this refers to the current element.

$("#submitBtn").prop("disabled", true);
$("input").prop("checked", true);

.prop() should be used instead of the .attr() to set disabled and checked values. The .val() method should be used for getting and setting value.

.removeProp()

Properties set by the .prop() method could be removed by .removeProp() method.

Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element.

Instead set these properties to false using .prop().

Advertisements

From → jQuery

3 Comments
  1. Good points

Trackbacks & Pingbacks

  1. jQuery attr & prop « ValueType

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: