jQuery attr() method

The jQuery attr() method get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

.attr( attributeName )

Description : Get the value of an attribute for the first element in the set of matched elements.

Source Code

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
   <style>
 	 .highlight { border : 2px solid #1E8CBE; }
  </style>
</head>
<body>
  
<div class="div1" title="Hello World!!!">Div 1</div>
<div class="div2">Div 2</div>

<button id="button1">Get Attribute Value</button>
  
<script>
jQuery("#button1").click(function () {
	var val = jQuery(".div1").attr("title");
	jQuery(".div2").text(val);
	jQuery(".div2").addClass("highlight");
});

</script>
</body>
</html>

Demo

Following example finds “title” attribute of the div (having div1 class).

Div 1
Div 2

.attr( attributeName, value )

Description : Set one or more attributes for the set of matched elements.

Source Code

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
   <style>
 	 .highlight { border : 2px solid #1E8CBE; }
  </style>
</head>
<body>
  
<div class="div1" title="Hello World!!!">Div 1</div>
<div class="div2">Div 2</div>

<button id="button2">Set Attribute Value</button>

  
<script>
jQuery("#button2").click(function () {
	jQuery(".div1").attr('title', 'Hello World 2!!!');
	var val = jQuery(".div1").attr("title");
	jQuery(".div2").text(val);
	jQuery(".div2").addClass("highlight");
});
</script>
</body>
</html>

Demo

Following example sets “title” attribute of the div (having div1 class).

Div 1
Div 2

,

No comments yet.

Leave a Reply