Você está na página 1de 12

jQuery Fun n Games with

Selectors

Learning Objectives
By the end of this lecture, you should be able to:
Comfortably use jQuery to select based on tag name, ID name, class
name
Select using descendant selectors
Comfortably look up and apply selections using various attribute
selectors
Comfortably look up and apply selections using filters
Understand how to apply multiple functions to a single selection on a
single line using chaining.

Selecting based on Element, ID, and Class names

ID: Suppose you had a div tag withan id of contact_info. You could select this ID in
the typical JavaScript way using:
document.getElementById('#contact_info');

Or you can do it the jQuery way:

$('#contact_info');

Element: To select an element (a, img, p, h2, etc) using JavaScript:


document.getElementsByTagName('h2');

The jQuery way:

$('h2');

Class: While it selecting based on class is certainly doable using standard JavaScript,
this is one of the many cases in which results can vary depending on the browser being
used. So we will forgo discussion on how to do it using JS for now.
The jQuery way:

$('.name_of_the_class');
EXAMPLE: To hide all elements to which the class navItem has been applied:

$('.navItem').hide();

Selector flexibility Descendant Selectors


Lets start taking a look at ways in which you can use jQuery selectors to really get in there and
pinpoint selections you want to work with.
Descendant selectors: A way to select all items that are contained within another item. This is more
powerful than you might initially think. For example, say you have a list of items with an ID of
favoriteFruit like so: <ol id="favoriteFruit"> and wish to select all of the images present
inside that list so that you can resize them. You could select all of the img tags within this id using:

$('#favoriteFruit img')
The key here is the order: First you select the main item, then place a space, and then the inside item. In
the example above, we first select the favoriteFruit id. We then place a space followed by img.
The result is that all images anywhere inside a tag with an ID of favoriteFruit will be selected.
You can then do something such as:
$('#favoriteFruit img').width('50px');
$('#favoriteFruit img').height('50px');
//will set all images inside the favoriteFruit ID section
//to 50 pixels high and wide
$('#navigationBar a').hide();
//will hide all hyperlinks inside the
//section that has an ID called navigationBar

EXAMPLE: descendent_selectors.htm

Selector flexibility Child Selectors


Child selectors: Similar to descendent selectors. However, with this one, you select only those
instances of a certain tag (or ID, or class) that are directly (i.e. first descendent only) within another
tag. You probably wont use this much, but its worth knowing about . This technique also serves as a
good example of the kinds of ways in which you can finesse your selections.
To create a child selector, you first name the parent item, then a >, and then the child item:
$('body > p');
//selects every p tag directly (i.e. not nested) within body
$('#footer > h1');
//selects every h1 directly within a section with id=footer
$('body > strong');
//NOTHING IS SELECTED!!! strong is not a direct descendent of body

Quick look at the onclick attribute


For many of you, the only value you have seen provided to the onclick attribute is a
function. For example:
<input type= "button" value= "Greet Me" onclick= "greetUser()">

However, there are many other scripting commands besides function calls that you can
provide as the value to onclick. For example:
<input type= "button" value= "Greet Me" onclick= "alert('Hello!')">

Two important notes about the value of the onlcick attribute:


Only relatively simple scripting commands can or should be used as the value to the
onclick attribute. If you have any complex scripting to do, you should place that
script inside a function and invoke the function via the onclick attribute.
We do not place a semicolon at the end of the scripting command.

Selector flexibility Attribute Selectors


This is where you select elements based on whether or not a certain attribute is present. For example, you might
search for img tags that contain the alt attribute. You can even get more powerful by searching, say, for those
images that have a width attribute greater than 200 pixels. Or you can select images whose src values contain the
text ball (e.g. redBall, greenBall, blueBall, etc).
So, attribute selectors can be quite powerful. Because of the large number of attribute selectors and the amount of
detail, a textbook or reference site should be your resource for really learning about them. However, I will go over a
few examples here.
$('img[alt]');
//selects images that include an alt attribute
$('input[type="radio"]');

//selects all radio buttons

$('img[src^="ball"]');
//selects images that have an src that begins with the word ball
//e.g. ballOfWax.jpg, ballAndChain.jpg, balloon.jpg, etc
$('img[src*="ball"]');
//selects images that have an src that contains the word ball
//e.g. redball.jpg, greenball.jpg, balloon.jpg (!), etc
$('a[href$=".ppt"]');
//selects all hyperlinks that end with the text .ppt
//e.g. lecture1.ppt, intro_to_jquery.ppt, etc

jQuery Filters When working with the DOM


So far we have learned to select based on an ID, a class name, and a tag. We then learned that we can further
refine our selections based on whether or not an attribute is present, and even based on the specific value of an
attribute.
We will now learn another tool for refining our selections through the use of filters. Filters are primarily used when
working with the document object model (DOM). For the moment then, we will limit our discussion to this one
slide. This tool is in many ways very similar to the selecting techniques we just demonstrated when we searched for
certain attribute values. We filter in jQuery through the use of a colon :
As usual, the best way to illustrate is through some examples:
$('p:first'); //selects the first paragraph on a page
$('p:last'); //selects the last paragraph on a page

$('p:not(.emphasize)');
//selects every paragraph on a page that does NOT apply the .emphasize class
$('li:has(a)'); //selects every list item that contains a hyperlink
$('li:contains("hockey")');
//selects every list item that contains the word hockey
$('a:not([href$=".ppt"])');
//selects every anchor tag that does NOT link to a powerpoint file
$('li:hidden'); //selects every list item that is hidden
//For example, if you have hidden some items previously, you can
//make them visible again with: $('li:hidden').show();

Selections often return a list


As you have seen, a jQuery selection often returns an entire list of items instead of one
single item. When you apply a function to a selection, jQuery doesnt care if the selection
is one item or an entire list of items. It will simply apply the function to whatever was
returned by the selection.
For example, suppose you want to hide all of the images on a page, you could do so with
the following code:
$('img').hide();
//The $('img') selects all the images on the page.
//The hide() function is applied to ALL items in the selection
//An impressively quick and simple way of doing things!!

Examples
The following will hide all of the images on a page
$('img').hide();

Suppose you wanted to limit this list so that you only hide images that include an alt
attribute:
$('img[alt]').hide();

Suppose you wanted to further limit this list so that you only hide images that include an
alt attribute that has the word ball anywhere inside of it:
$('img[alt*="ball"]').hide();

NOTE: This steps used in these examples also serve as a great way to show you how to
get jQuery to work the way you want it to. That is, start with your selection as simple and
broad as you can. Then work on refining your selection further and further, testing your
page each time, until you get it to work the way you want it to.

Chaining functions
If you want to do several operations on a selection, you could write out each function one
at a time OR, you could simply concatenate the functions, one after the other.
Example: Suppose you want to take all of the images on a page and set them to the
identical size (lets say width=200 pixels, and height = 200 pixels), and then fade them in
over 1 second. You could do so with:
$('img').width(200);
$('img').height(200);
$('img').fadeIn(1000);

Instead, however, you could save time and space by chaining the functions together like
so:
$('img').width(200).height(200).fadeIn(1000);

This is not simply cosmetic. Chaining functions turns out to be faster and more efficient.
We will discuss more about efficient coding as we progress through the course. For now,
however, if you have a group of related functions that you are planning on applying to a
particular selection, you should try and chain them.

File: selectors_contd.htm

Você também pode gostar