Cover Image for jQuery prop() method
85 views

jQuery prop() method

The jQuery prop() method is used to get or set properties of HTML elements. It allows you to retrieve the value of a property or set a new value for the property on the selected elements.

The syntax for using the prop() method is as follows:

To Get Property Value:

$(selector).prop(propertyName);

To Set Property Value:

$(selector).prop(propertyName, value);
  • selector: It is a string that specifies the elements to be selected.
  • propertyName: It is a string representing the name of the property you want to get or set.
  • value (optional): It is the value that you want to set for the property.

Here’s an example of how you can use the prop() method:

HTML:

<input type="checkbox" id="myCheckbox" checked>

JavaScript:

// Get the value of the "checked" property of the checkbox
var isChecked = $('#myCheckbox').prop('checked');
console.log('Is Checked: ' + isChecked);

// Set a new value for the "checked" property of the checkbox
$('#myCheckbox').prop('checked', false);

In the above example, the prop() method is used to get the value of the “checked” property of the checkbox element with the ID “myCheckbox” and log it to the console. Then, the prop() method is used again to set a new value (false) for the “checked” property of the same checkbox.

After using the prop() method to set the new value, the resulting HTML would look like this:

<input type="checkbox" id="myCheckbox">

Unlike the attr() method, the prop() method deals specifically with properties, not attributes. Properties are generally used for non-standard attributes or special element properties, such as checked, disabled, selected, etc. For standard HTML attributes, it’s generally better to use attr().

When using prop() to set a property value, it will update the property on all matched elements. If you only want to modify the property on the first element in the selected set, you can use the eq() method or index the selection.

It’s important to note that while the attr() method returns the attribute value as a string, the prop() method returns the property value in its native type. For example, the “checked” property of a checkbox will return a boolean value (true or false). So, when using prop() to check for property values, remember to compare with appropriate data types.

if ($('#myCheckbox').prop('checked')) {
  // Checkbox is checked
}

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS