attr() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:attr

Description

The attr() method sets or returns attributes and values of the selected elements.

Syntax

$(selector).attr(attribute, value, function(index, currentvalue));
ParameterDescription
attributeSpecifies the name of the attribute
valueSpecifies the value of the attribute
function(index,currentvalue) Specifies a function that returns the attribute value to set
  • index - the index position of the element in the set
  • currentvalue - the current attribute value of selected elements

The following code shows how to set the width attribute of an image:

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(){
        $("img").attr("width", "500");
    });//from www .  j a v  a 2s  . c  o m
});
</script>
</head>
<body>

<img src="http://java2s.com/resources/a.png" alt="message" width="300" height="213"><br>

<button>Set the width attribute of the image</button>

</body>
</html>

Related Tutorials