prop() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:prop

Description

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

When returning the property value, it returns the value of the FIRST matched element.

When setting property values, it sets one or more property/value pairs for the set of matched elements.

Syntax

ParameterDescription
property the name of the property
valuethe value of the property
function(index,currentvalue) a function that returns the property value to set
  • index - Receives the index position of the element in the set
  • currentvalue - Receives the current property value of selected elements

The following code shows how to Add and remove a property named "color":

Demo Code

ResultView the demo in separate window

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

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

<div></div>

</body>
</html>

Related Tutorials