jQuery prop() method is used for two purpose.
The jQuery prop() method is generally used to retrieve property values i.e. DOM properties (like tagName, nodeName, defaultChecked) or own custom made properties. This is a very convenient way to set the values of properties, especially the multiple properties.
If you want to retrieve HTML attributes, you should use the attr() method instead.
Syntax:
To return the value of a property:
$(selector).prop(property)
To set the property and value:
$(selector).prop(property,value)
To set property and value by using a function:
$(selector).prop(property,function(index,currentvalue))
To set multiple properties and values:
$(selector).prop({property:value, property:value,...})
Parameter | Description |
---|---|
Property | It specifies the name of the property. |
Value | It defines the value of the property. |
Function(index, currentvalue) | It specifies a function which returns the value of the property to set.
|
Let's see a simple example of jQuery prop() method.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ var $x = $("div"); $x.prop("color","#e0eeee"); $x.append("The value of the color property: " + $x.prop("color")); $x.removeProp("color"); $x.append("<br>Now the value of the color property: " + $x.prop("color")); }); }); </script> </head> <body> <button>Add and remove a property</button><br><br> <div></div> </body> </html>
Let's see another example of jQuery prop() method.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>prop demo</title> <style> p { margin: 20px 0 0; } b { color: red; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <input id="check1" type="checkbox" checked="checked"> <label for="check1">Check me</label> <p></p> <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> </body> </html>
This is a very common question because most of the people are confused about where to use prop() method and where attr() method. The differences between them are very important in specific situation.
Following is the exact differences between them: