jQuery Kochbuch

Page 53

method by passing the method the attribute name alone. Had there been multiple <a> elements in the document, the attr() method would access the first matched element. The code when loaded into a browser will alert() the value that we set for the href attribute. Now, since most elements have more than one attribute available, it’s also possible to set multiple attribute values using a single attr() method. For example, we could also set the title attribute in the previous example by passing the attr() method an object instead of two string parameters: jQuery('a').attr({'href':'http://www.jquery.com','title':'jquery.com'}).attr('href')

With the ability to add attributes to elements also comes the ability to remove attributes and their values. The removeAttr() method can be used to remove attributes from HTML elements. To use this method, simply pass it a string value of the attribute you’d like to remove (e.g., jQuery('a')removeAttr('title')).

Discussion In addition to the attr() method, jQuery provides a very specific set of methods for working with the HTML element class attribute. Since the class attribute can contain several values (e.g., class="class1 class2 class3"), these unique attribute methods are used to manage these values. These jQuery methods are as follows: addClass()

Updates the class attribute value with a new class/value including any classes that were already set hasClass()

Checks the value of the class attribute for a specific class removeClass()

Removes a unique class from the class attribute while keeping any values already set toggleClass()

Adds the specified class if it is not present; removes the specified class if it is present

1.15 Getting and Setting HTML Content Problem You need to get or set a chunk of HTML content in the current web page.

30 | Chapter 1: jQuery Basics


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.