02.06.2013 Views

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

method by passing the method the attribute name alone. Had there been multiple<br />

elements in the document, the attr() method would access the first matched element.<br />

The code when loaded into a browser will alert() the value that we set for the<br />

href attribute.<br />

Now, since most elements have more than one attribute available, it’s also possible to<br />

set multiple attribute values using a single attr() method. For example, we could also<br />

set the title attribute in the previous example by passing the attr() method an object<br />

instead of two string parameters:<br />

<strong>jQuery</strong>('a').attr({'href':'http://www.jquery.<strong>com</strong>','title':'jquery.<strong>com</strong>'}).attr('href')<br />

With the ability to add attributes to elements also <strong>com</strong>es the ability to remove attributes<br />

and their values. The removeAttr() method can be used to remove attributes from<br />

HTML elements. To use this method, simply pass it a string value of the attribute you’d<br />

like to remove (e.g., <strong>jQuery</strong>('a')removeAttr('title')).<br />

Discussion<br />

In addition to the attr() method, <strong>jQuery</strong> provides a very specific set of methods for<br />

working with the HTML element class attribute. Since the class attribute can contain<br />

several values (e.g., class="class1 class2 class3"), these unique attribute methods<br />

are used to manage these values.<br />

These <strong>jQuery</strong> methods are as follows:<br />

addClass()<br />

Updates the class attribute value with a new class/value including any classes that<br />

were already set<br />

hasClass()<br />

Checks the value of the class attribute for a specific class<br />

removeClass()<br />

Removes a unique class from the class attribute while keeping any values already<br />

set<br />

toggleClass()<br />

Adds the specified class if it is not present; removes the specified class if it is present<br />

1.15 Getting and Setting HTML Content<br />

Problem<br />

You need to get or set a chunk of HTML content in the current web page.<br />

30 | Chapter 1: <strong>jQuery</strong> Basics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!