www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons jQuery attr() Method Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27

Getting / Setting attributes is also very simple using jQuery. jQuery provides us the attr() method that enables us to change / modify one or more attributes of an element.

The jQuery attr() Method, in its simplest form takes one parameter i.e the name of the attribute we wish to get.

Here is a very simple example:

<a href="http://pickatutorial.com" id = "homepage" > Computer Programming Tutorials </a>
<script type = "text/javascript" >
$ ( function ()
{
alert ( $ ( "#homepage" ). attr ( "href" ));
});
</script>

When we run the above example, it gets the value of href attribute of our <a> tag and displays the same in an alert box.

There is another point to note in the above example. Recall that in one of our earlier lessons we learned the use of the document.ready() event. The above syntax of passing the function to the constructor of the jQuery is an alternative way of telling jQuery to call the passed function when the document is ready and loaded fully.

To modify the attribute, we just need to supply an extra parameter to the attr() method. See the following example:

<a href="http://cprogramming.pickatutorial.com" id = "homepage" > Computer Programming Tutorials </a>
<script type = "text/javascript" >
$ ( function ()
{
alert ( "Before Modification: " + $ ( "#homepage" ). attr ( "href" ));
$("#homepage" ). attr( "href", "http://pickatutorial.com" );
alert ("After Modification: " + $ ( "#homepage" ). attr ( "href" ));
});
</script>

The above example changes the href attribute from http://cprogramming.pickatutorial.com to http://pickatutorial.com.

We can also supply a map of name/value pairs to the attr() method to change multiple attributes simultaneously. In the following example we set the href and target attributes of the <a> tag, simultaneously:

<a href="http://cprogramming.pickatutorial.com" id = "homepage" target="_self"> Computer Programming Tutorials </a>
<script type = "text/javascript" >
$ ( function ()
{
$("#homepage" ). attr( {"href" : "http://pickatutorial.com",
"target" : "_blank" } );
});
</script>

Next >>> Lesson No. 17: jQuery Working With CSS





Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.