- jQuery Traversing
- What is Traversing?
Getting and setting attributes [attr()]
In previous chapter, we saw how easy it was to get and set HTML and text content from and to an element. Luckily, changing one or more attributes of an element is just as easy. We use attr() method for this, which takes one parameter in its simplest form: Name of the attribute we wish to get:
This will change the link to point to British version of Google. attr() method can also take a map of name/value pairs, for setting up multiple attributes at the same time. Here we set both the href and title attributes simultaneously:
<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 />
$("a.google").attr("href", function(index, oldValue)
return oldValue + "imghp?tab=wi";
We simply change all Google links to point to the Image search instead of default page, by adding an extra parameter to href attribute. In this example we do not really use the index parameter, but we could have it if needed, to tell us which index in the list of elements selected we are currently dealing with.