jQuery attr() attribute method function


jquery jQuery attr() attribute method function Jquery Functions

How to get access and modified the attribute value of the HTML tag?

We can easily access the attributes of HTML tags and we can easily modified the attributes of HTML tags using the jQuery attr() function.

Syntax of jQuery attr() function

For getting the value of attribute. $("TagSelector").attr("attributeName"); For assigning the attribute value. $("TagSelector").attr("attributeName","Attribute value"); We are considering two examples , example to fetch the tag attribute value and example to assign the value to the attribute of tag.

1- On button click Get the image's attribute " width " and alert the width value

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button> Get image Width </button> <img width='500' src='https://codingpk.com/images/CodingPk-Logo.png' /> <script type="text/javascript"> $("button").click(function() { var width = $("img").attr("width"); alert(width); }); </script>

Output of getting attribute Value

2- Onclick assign the width value 600px using jQuery attr() function

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button> Set image Width 600 px </button> <img width='500' src='https://codingpk.com/images/CodingPk-Logo.png' /> <script type="text/javascript"> $("button").click(function() { $("img").attr("width","600"); }); </script>

Output of setting attribute Value

Note. We can assign multiple attribute using jQuery function attr(). $("img").attr({ "width":"600","border":"10" });
jquery Jquery Functions Chapter Next »