-->

jQuery attr() Method

By: Bipin C Mathew 4 months, 3 weeks ago

The attr() is a Jquery HTML/CSS Method. It is used to set or return attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements. The parameters used in this method are attribute  - Specifies the name of the attribute, valueSpecifies the value of the attribute, function(index,currentvalue)Specifies a function that returns the attribute value to set.

Syntax 

$(selector).attr(attribute)  - Return the value of an attribute.

$(selector).attr(attribute,value) - Set the attribute and value.

$(selector).attr(attribute,function(index,currentvalue))  - Set attribute and value using a function.

$(selector).attr({attribute:valueattribute:value,...})  - Set multiple attributes and values.

Example

	<!doctype html>
	<html lang="en">
		<head>
			<meta charset="utf-8">

			<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
			<script>  
				$(document).ready(function(){  
				    $("button").click(function(){  
					  $("img").attr("width", "500");  
				    });  
				});  
			</script>  
		</head>
		<body>
			<img src="https://cdn.mos.cms.futurecdn.net/HEaNzTyXysVof6GEcvhNdH-970-80.jpg"width="284" height="213"><br>
			<button>Set the width attribute of the image</button>  
		</body>
	</html>

Describtion
In this code jquery is started with $(document).ready(function() . it is used to identify Document Object Model (DOM) is ready for JavaScript code to execute. The $("button").click(function(){ $("img").attr("width", "500"); when we click the button the image width changes to 500px.

Comments

Let us talk!

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.