Set the width attribute of an image:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>//from ww w .j av a 2s. c om <script> $(document).ready(function(){ $("button").click(function(){ $("img").attr("width", "200"); }); }); </script> </head> <body> <img src="image4.png" alt="image4.png" width="100" height="200"><br> <button>Set the width attribute of the image</button> </body> </html>
The attr()
method sets or gets attributes and values of the selected elements.
As getter, it returns the value of the first matched element.
As setter, it sets one or more attribute/value pairs for the set of matched elements.
Return the value of an attribute:
$(selector).attr(attribute)
Set the attribute and value:
$(selector).attr(attribute,value)
Set attribute and value using a function:
$(selector).attr(attribute,function(index,current_value))
Set multiple attributes and values:
$(selector).attr({attribute:value, attribute:value,...})
Parameter | Description |
---|---|
attribute | the name of the attribute |
value | the value of the attribute |
function(index,current_value) | sets a function that returns the attribute value to set index - the index position of the element in the set current_value - the current attribute value of selected elements |