why are use the attr function in JQuery? explain with example.

0 votes
60 views
Ethan Karla asked 28-Jul-2021 in Web Application by Ethan Karla

why are use the attr function in JQuery? explain with example.    

1 Answer

1 votes
Ravi Vishwakarma answered 29-Jul-2021 by Ravi Vishwakarma
Jquery attr() is used to set and get the attribute properties of a selected element, such as width, height, select, and others.
Syntax

$(selector).attr(attribute)        
return attribute and value
$(selector).attr(attribute,value)
set an attribute and value
$(selector).attr(attribute,function(index,currentvalue))
set multiple attributes and values using function
$(selector).attr({attribute:value, attribute:value,...})
Example 
<!DOCTYPE html>  

<html lang='en'>
<head>
  <meta charset='utf-8'>
  <title>scrollTop demo</title>
  <script src='https://code.jquery.com/jquery-1.10.2.js'></script>
<script>
    $(document).ready(function () {
        $('button').click(function () {
            $('img').attr({ width: 100}).show(1000);
        });
    });
</script>
</head>
<body>
<img src='https://source.unsplash.com/1600x900/?nature,water' width='500px' ><br>
<button>Set the width attribute of the image</button>
</body>
</html>  

Output:

why are use the attr function in JQuery? explain with example.