jQuery prop() method
Example
Add and remove a property named "color":
$
(
"
button
"
)
.
click
(
function
(
)
{
var
$
x
= $
(
"
div
"
)
; $
x
.
prop
(
"
color
"
,
"
FF0000
"
)
; $
x
.
append
(
"
The color property:
"
- $
x
.
prop
(
"
color
"
)
)
; $
x
.
removeProp
(
"
color
"
)
;
}
)
;
Try it »
Definition and Usage
The prop() method sets or returns the properties and values of the selected elements.
When this method is used toReturnproperty value, it returns the value of the first matched element.
When this method is used toSettingsproperty value, it sets one or more property/value pairs for the set of matched elements.
**Note:** The prop() method should be used to retrieve property values, such as DOM properties (e.g., selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected).
**Tip:** To retrieve HTML attributes, use attr() method instead.
**Tip:** To remove a property, use removeProp() method.
Syntax
Returning the value of an attribute:
$(
selector
).prop(
property
)
Setting an attribute and value:
$(
selector
).prop(
property,value
)
Setting attributes and values using a function:
$(
selector
).prop(
property,
function(
index,
currentvalue
))
Set multiple properties and values:
$(
selector
).prop({
property
:
value
,
property
:
value
,...})
| Parameters | Description |
|---|---|
| property | Specifies the name of the attribute. |
| value | Specifies the value of the attribute. |
| function(index,currentvalue) | Specifies a function that returns the property value to set.
|
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 methods