jQuery prop()Method

jQuery HTML/CSS 方法jQuery HTML/CSS Methods

Example

Add and remove an attribute named "color":

$("button").click(function(){ var $x = $("div"); $x.prop("color","FF0000"); $x.append("The color attribute:" + $x.prop("color")); $x.removeProp("color"); });

Try it Yourself »

Definition and Usage

The prop() method sets or returns attributes and values of the selected elements.

When this method is used toreturnattribute values, it returns the value of the first matched element.

When this method is used tosetattribute values, it sets one or more attribute/value pairs for the set of matched elements.

Note:The prop() method should be used to retrieve attribute values, such as DOM properties (like selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected).

Tip:To retrieve HTML attributes, use the attr()method instead.

Tip:To remove attributes, use theremoveProp()method.


Syntax

Return the value of an attribute:

$(selector).prop(property)

Set attribute and value:

$(selector).prop(property,value)

Set attribute and value using a function:

$(selector).prop(property,function(index,currentvalue))

Set multiple attributes and values:

$(selector).prop({property:value, property:value,...})

Parameter Description
property Specifies the name of the attribute.
value Specifies the value of the attribute.
function(index,currentvalue) Specifies a function that returns the attribute value to set.
  • index- The index position of the element in the set.
  • currentvalue- The current attribute value of the selected element.


实例

More Examples

The difference between prop() and attr()
prop() and attr() may return different values. This example demonstrates the difference when used to return the "checked" state of a checkbox.


jQuery HTML/CSS 方法jQuery HTML/CSS Methods

Other Extensions