The jQuery attr() method is used to set or get the attributes or values of the selected elements.
Syntax of attr() method
This returns the value of the specified attribute:
$(selector).attr(attribute)
This sets the attribute and value of the selected elements:
$(selector).attr(attribute,value)
This sets the attribute and value of the selected elements using a function:
$(selector).attr(attribute,function(index,value))
This sets multiple attributes and values:
$(selector).attr({attribute:value, attribute:value,...})
Example 1: jQuery attr(): return attribute value
In this example, we are finding the width of an image using the attr()
method. The attr() method returns the value of the image width attribute.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Image width: " + $("img").attr("width"));
});
});
</script>
</head>
<body>
<img src="beginnersbook_logo.png" alt="Website" width="520" height="180"><br>
<button>Find width of the image</button>
</body>
</html>
Output:
Before the button click:
After the button click:
Example 2: jQuery attr() method to set attribute value
In this example, we are setting the width value using attr() method. Here attribute is “width” and the value is “current width – 150px”.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("img").attr("width",function(n, v){
return v - 150;
});
});
});
</script>
</head>
<body>
<img src="beginnersbook_logo.png" alt="Website" width="520" height="180"><br>
<button>Decrease image width by 150px</button>
</body>
</html>
Output:
Before the button click:
After the button click:
Example 3: Setting multiple attribute and value pairs
In this example, we are setting multiple attribute and value pairs. We are setting multiple attributes (width & height) and multiple values for the img
element.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("img").attr({width: "260", height: "90"});
});
});
</script>
</head>
<body>
<img src="beginnersbook_logo.png" alt="Website" width="520" height="180"><br>
<button>Set image width to 260px and height to 90px</button>
</body>
</html>
Output:
Before the button click:
After the button click:
Leave a Reply