Difference between ‘prop’ and ‘attr’ in JQuery?

Last updated:9/18/2020 11:15:16 PM

1 Answers

Harsh kumar srivastava
Harsh kumar srivastava

Major difference between ‘prop’ and ‘attr’ , we can get value of custom attributes by using attribute (attr) but we can’t get value of custom attribute by using ‘prop’.


We only get pre-defined attributes value by ‘prop’ but we can’t able to get value of custom attribute by using ‘prop’.


Example of 'prop':


<!DOCTYPE html>
 
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Difference Between prop and attr in JQuery </title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
        $(function () {
            console.log($('#txtName').prop("id"));
        });
    </script>
</head>
<body>
    <input type="text" name="txtName" id="txtName" value="Pawan" pawan="Pawan Shukla" />
</body>
</html>

 

Example of 'attr':

 

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Difference Between prop and attr in JQuery </title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
        $(function () {
            console.log($('#txtName').attr("pawan"));
        });
    </script>
</head>
<body>
    <input type="text" name="txtName" id="txtName" value="Pawan" pawan="Pawan Shukla" />
</body>
</html>

Answer