jQuery prop()

Introduction

Add and remove a property named "color":

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>/*  w w  w .j a  v a 2s  .  c o m*/
<script>
$(document).ready(function(){
  $("button").click(function(){
    let $x = $("div");
    $x.prop("color", "red");
    $x.append("property value: " + $x.prop("color"));
    $x.removeProp("color");
    $x.append("<br>color property: " + $x.prop("color"));
  });
});
</script>
</head>
<body>

<button>Add and remove a property</button><br><br>

<div></div>

</body>
</html>

The prop() method sets or gets properties and values of the selected elements.

As getter, it returns the value of the first matched element.

As setter, it sets one or more property/value pairs for the set of matched elements.

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

Return the value of a property:

$(selector).prop(property)

Set the property and value:

$(selector).prop(property,value)

Set property and value using a function:

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

Set multiple properties and values:

$(selector).prop({property:value,
                  property:value,...})
Parameter
Description
property
the name of the property
value
the value of the property
function(index,current_value)


sets a function that returns the property value to set
index - the index position of the element in the set
current_value - the current property value of selected elements



PreviousNext

Related