TOC
Need to learn JavaScript? jQuery is a JavaScript framework, so if you don't already know about the JavaScript programming language, we recommend that you learn it now: Learn JavaScript
DOM manipulation:

Getting and setting attributes [attr()]

In the previous chapter, we saw how easy it was to get and set text and HTML content from and to an element. Fortunately, changing one or more attributes of an element is just as easy. We use the attr() method for this, which in its simplest form takes one parameter: The name of the attribute we wish to get:

<a href="http://www.google.com" id="aGoogle1">Google Link</a>
<script type="text/javascript">
$(function()
{
	alert($("#aGoogle1").attr("href"));
});
</script>

In this example, we get the value of the "href" attribute of our link and then show it to the user. To change an attribute, we simply specify an extra parameter:

<a href="http://www.google.com" id="aGoogle2">Google Link</a>
<script type="text/javascript">
$(function()
{
	$("#aGoogle2").attr("href", "http://www.google.co.uk");
});
</script>

This will change the link to point to the British version of Google. The attr() method can also take a map of name/value pairs, for setting multiple attributes at the same time. Here we set both the href and the title attributes simultaneously:

<a href="http://www.google.com" id="aGoogle3">Google Link</a>
<script type="text/javascript">
$(function()
{
	$("#aGoogle3").attr(
	{ 
		"href" : "http://www.google.co.uk", 
		"title" : "Google.co.uk"
	});
});
</script>

The attr() method also supports the special overload where the value parameter is instead a callback function, allowing you to access the index of the element selected as well as the existing attribute value. Here's an example of just that:

<a href="http://www.google.com/" class="google">Google.com</a><br />
<a href="http://www.google.co.uk/" class="google">Google UK</a><br />
<a href="http://www.google.de/" class="google">Google DE</a><br />

<script type="text/javascript">
$(function()
{
	$("a.google").attr("href", function(index, oldValue)
	{
		return oldValue + "imghp?tab=wi";
	});
});
</script>

We simply change all the Google links to point to the Image search instead of the default page, by adding an extra parameter to the href attribute. In this example we don't really use the index parameter, but we could have if we needed it, to tell us which index in the list of elements selected we're currently dealing with.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!