Description a and attributes represents href, target, id, class, title each of which consists of a name and value.
jQuery easily access the attributes of elements and manipulate the attributes of elements. So that, one can easily change the properties or attributes of elements.
Description
Syntax
Description attr() method can be used to either get value of attribute from the specified element or set a value of attributes onto all matched elements.
The attr(name) method can be used to select the value of attribute from the specified element of the document.
Example title attribute from p element.
[html]
<html>
<head>
<title>jQuery First Application</title>
</head>
<body>
<h1>Welcome to SPLessons</h1>
<p title="this is title of paragraph">click on this paragraph</p>
</body>
</html>
[/html]
[javascript]
$(document).ready(function(){
$("p").click(function(){
var title = $(this).attr("title");
alert(title);
});
});
[/javascript]
Output:
Description attr(name, value) method can be used to set the value of name attribute from specified element of HTML document.
Example href attribute from a tag of HTML document changed.
[html]
<html>
<head>
<title>jQuery First Application</title>
</head>
<body>
<h1>Welcome to SPLessons</h1>
<a href="#">SPLessons</a>
<button>change href value</button>
<p>Mouse over the link to see that the value of the href attribute has changed.</p>
</body>
</html>
[/html]
[javascript]
$(document).ready(function(){
$("button").click(function(){
$("a").attr("href","http://www.splessons.com");
alert("The value of href attribute changed");
});
});
[/javascript]
Output:
Key Points