Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

jQuery

Learn step by step



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:


<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 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.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 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.



Related Videos