• 沒有找到結果。

Selecting the elements upon which to act

在文檔中 IN ACTIONSECOND EDITION (頁 51-88)

In the previous chapter, we discussed the many ways that the jQuery function can be used. Its capabilities range from the selection of DOM elements to defining func-tions to be executed when the DOM is loaded.

In this chapter, we’ll examine (in great detail) how the DOM elements to be acted upon are identified by looking at two of the most powerful and frequently used capabilities of jQuery’s $() function: the selection of DOM elements via selec-tors and the creation of new DOM elements.

A good number of the capabilities required by interactive web applications are achieved by manipulating the DOM elements that make up the pages. But before they can be manipulated, they need to be identified and selected. Let’s begin our detailed tour of the many ways that jQuery lets us specify which elements are to be targeted for manipulation.

This chapter covers

ƒ Selecting elements to be wrapped by jQuery using selectors

ƒ Creating and placing new HTML elements in the DOM

ƒ Manipulating the wrapped element set

19 Selecting elements for manipulation

2.1 Selecting elements for manipulation

The first thing we need to do when using virtually any jQuery method (frequently referred to as jQuery wrapper methods) is to select some document elements to act upon. Sometimes, the set of elements we want to select will be easy to describe, such as

“all paragraph elements on the page.” Other times, they’ll require a more complex description like “all list elements that have the class listElement, contain a link, and are first in the list.”

Fortunately, jQuery provides a robust selector syntax we can use to easily specify sets of elements elegantly and concisely. You probably already know a big chunk of the syn-tax: jQuery uses the CSS syntax you already know and love, and extends it with some custom means to perform both common and complex selections.

Figure 2.1 The jQuery Selectors Lab Page allows you to observe the behavior of any selector you choose in real time.

20 CHAPTER 2 Selecting the elements upon which to act

To help you learn about element selection, we’ve put together a jQuery Selectors Lab Page that’s available within the downloadable code examples for this book (in file chapter2/lab.selectors.html). The Selectors Lab allows you to enter a jQuery selector string and see (in real time!) which DOM elements get selected. When displayed, the Lab should look as shown in figure 2.1 (if the panes don’t appear correctly lined up, you may need to widen your browser window).

TIP If you haven’t yet downloaded the example code, you really ought to do so now—the information in this chapter will be much easier to absorb if you follow along with the Lab exercises. Visit this book’s web page at http://

www.manning.com/bibeault2 to find the download link.

The Selector pane at top left contains a text box and a button. To run a Lab “experi-ment,” type a selector into the text box and click the Apply button. Go ahead and type the string li into the box, and click the Apply button.

The selector that you type (in this case li) is applied to the HTML fragment loaded into the DOM Sample pane at upper right. The Lab code that executes when Apply is clicked adds a class named wrappedElement to be applied to all matching elements. A CSS rule defined for the page causes all elements with that class to be highlighted with a red border and pink background. After clicking Apply, you should see the display shown in figure 2.2, in which all <li> elements in the DOM sample are highlighted.

Note that the <li> elements in the sample fragment have been highlighted and that the executed jQuery statement, as well as the tag names of the selected elements, have been displayed below the Selector text box.

The HTML markup used to render the DOM sample fragment is displayed in the lower pane, labeled DOM Sample Code. This should help you experiment with writing selectors targeted at the elements in this sample.

We’ll talk more about using this Lab as we progress through the chapter. But first, your authors must admit that they’ve been blatantly over-simplifying an important concept, and that’s going to be rectified now.

2.1.1 Controlling the context

Up to this point, we’ve been acting as if there were only one argument passed to jQuery’s $() function, but this was just a bit of hand waving to keep things simple at the start. In fact, for the variants in which a selector or an HTML fragment is passed to the $() function, a second argument is accepted. When the first argument is a selec-tor, this second argument denotes the context of the operation.

As we’ll see with many of jQuery’s methods, when an optional argument is omit-ted, a reasonable default is assumed. And so it is with the context argument. When a selector is passed as the first argument (we’ll deal with passing HTML fragments later), the context defaults to applying that selector to every element in the DOM tree.

That’s quite often exactly what we want, so it’s a nice default. But there may be times when we want to limit our search to a subset of the entire DOM. In such cases, we

21 Selecting elements for manipulation

can identify a subset of the DOM that serves as the root of the sub-tree to which the selector is applied.

The Selectors Lab offers a good example of this scenario. When that page applies the selector that you typed into the text field, the selector is applied only to the subset of the DOM that’s loaded into the DOM Sample pane.

We can use a DOM element reference as the context, but we can also use either a string that contains a jQuery selector, or a wrapped set of DOM elements. (So yes, that means that we can pass the result of one $() invocation to another—don’t let that make your head explode just yet; it’s not as confusing as it may seem at first.)

When a selector or wrapped set is provided as the context, the identified elements serve as the contexts for the application of the selector. As there can be multiple such elements, this is a nice way to provide disparate sub-trees in the DOM to serve as the contexts for the selection process.

Figure 2.2 A selector value of li matches all <li> elements when applied, as shown by the displayed results.

22 CHAPTER 2 Selecting the elements upon which to act

Let’s take the Lab Page as an example. We’ll assume that the selector string is stored in a variable conveniently named selector. When we apply this submitted selector, we only want to apply it to the sample DOM, which is contained within a

<div> element with an id value of sampleDOM.

Were we to code the call to the jQuery function like this,

$(selector)

the selector would be applied to the entire DOM tree, including the form in which the selector was specified. That’s not what we want. What we want is to limit the selection process to the sub-tree of the DOM rooted at the <div> element with the id of sample-DOM; so instead we write

$(selector,'div#sampleDOM')

which limits the application of the selector to the desired portion of the DOM. OK, now that we know how to control where to apply selectors, let’s see how to code them beginning with familiar territory: traditional CSS selectors.

2.1.2 Using basic CSS selectors

For applying styles to page elements, web developers have become familiar with a small, but powerful and very useful, group of selection expressions that work across all browsers. Those expressions can select by an element’s ID, by CSS class names, by tag names, and by the hierarchy of the page elements within the DOM.

Table 2.1 provides some examples to give you a quick refresher. We can mix and match these basic selector types to identify fairly fine-grained sets of elements.

With jQuery, we can easily select elements using the CSS selectors that we’re already accustomed to using. To select elements using jQuery, wrap the selector in

$(), like this:

$("p a.specialClass")

With a few exceptions, jQuery is fully CSS3 compliant, so selecting elements this way will present no surprises; the same elements that would be selected in a style sheet by a

Table 2.1 Some simple CSS selector examples

Example Description

a Matches all anchor (<a>) elements

#specialID Matches the element with the id value of specialID .specialClass Matches all elements with the class specialClass a#specialID.specialClass Matches the element with the id value specialID if it’s an

anchor tag and has class specialClass

p a.specialClass Matches all anchor elements with the class specialClass that are descendants of <p> elements

23 Selecting elements for manipulation

standards-compliant browser will be selected by jQuery’s selector engine. Note that jQuery does not depend upon the CSS implementation of the browser it’s running within. Even if the browser doesn’t implement a standard CSS selector correctly, jQuery will correctly select elements according to the rules of the World Wide Web Consortium (W3C) standard.

jQuery also lets us combine multiple selectors into a single expression using the comma operator. For example, to select all <div> and all <span> elements, you could do this:

$('div,span')

For some practice, play with the Selectors Lab and run some experiments with some basic CSS selectors until you feel comfortable with them.

These basic selectors are powerful, but sometimes we’ll need even finer-grained control over which elements we want to match. jQuery meets this challenge and steps up to the plate with even more advanced selectors.

2.1.3 Using child, container, and attribute selectors

For more advanced selectors, jQuery uses the most up-to-date generation of CSS sup-ported by Mozilla Firefox, Internet Explorer 7 and 8, Safari, Chrome and other mod-ern browsers. These advanced selectors allow us to select the direct children of some elements, elements that occur after other elements in the DOM, and even elements with attributes matching certain conditions.

Sometimes, we’ll want to select only the direct children of a certain element. For example, we might want to select list elements directly under some list, but not list ele-ments belonging to a sublist. Consider the following HTML fragment from the sample DOM in the Selectors Lab:

<ul class="myList">

<li><a href="http://jquery.com">jQuery supports</a>

<ul>

<li><a href="css1">CSS1</a></li>

<li><a href="css2">CSS2</a></li>

<li><a href="css3">CSS3</a></li>

<li>Basic XPath</li>

</ul>

</li>

<li>jQuery also supports <ul>

<li>Custom selectors</li>

<li>Form selectors</li>

</ul>

</li>

</ul>

Suppose that we wanted to select the link to the remote jQuery site, but not the links to various local pages describing the different CSS specifications. Using basic CSS selectors, we might try something like ul.myList li a. Unfortunately, that selector would grab all links because they all descend from a list element.

24 CHAPTER 2 Selecting the elements upon which to act

You can verify this by entering the selector ul.myList li a into the Selectors Lab and clicking Apply. The results will be as shown in figure 2.3.

A more advanced approach is to use child selectors, in which a parent and its direct child are separated by the right angle bracket character (>), as in

p > a

This selector matches only links that are direct children of a <p> element. If a link were further embedded, say within a <span> within the <p>, that link would not be selected.

Going back to our example, consider a selector such as

ul.myList > li > a

This selector selects only links that are direct children of list elements, which are in turn direct children of <ul> elements that have the class myList. The links contained in the sublists are excluded because the <ul> elements serving as the parent of the sublists’ <li> elements don’t have the class myList, as shown in the Lab results in fig-ure 2.4.

Attribute selectors are also extremely powerful. Say that we want to attach a special behavior only to links that point to locations outside your site. Let’s take another look at that portion of the Lab example that we previously examined:

<li><a href="http://jquery.com">jQuery supports</a>

<ul>

Figure 2.3 All anchor tags that are descendants, at any depth, of an <li> element are selected by ul.myListlia.

25 Selecting elements for manipulation

<li><a href="css2">CSS2</a></li>

<li><a href="css3">CSS3</a></li>

<li>Basic XPath</li>

</ul>

</li>

What makes the link pointing to an external site unique is the http:// at the begin-ning of the string value for the link’s href attribute. We could select links that have an href value starting with http:// with the following selector:

a[href^='http://']

This matches all links with an href value beginning with the exact string http://. The caret character (^) is used to specify that the match is to occur at the beginning of a value. As this is the same character used by most regular expression processors to sig-nify matching at the beginning of a candidate string, it should be easy to remember.

Visit the Lab page again (from which the previous HTML fragment was lifted), type a[href^='http://'] into the text box, and click Apply. Note how only the jQuery link is highlighted.

There are other ways to use attribute selectors. To match an element that possesses a specific attribute, regardless of its value, we can use

form[method]

This matches any <form> element that has an explicit method attribute.

To match a specific attribute value, we use something like

input[type='text']

Figure 2.4 With the selector ul.myList>li>a, only the direct children of parent nodes are matched.

26 CHAPTER 2 Selecting the elements upon which to act

This selector matches all input elements with a type of text.

We’ve already seen the “match attribute at beginning” selector in action. Here’s another:

div[title^='my']

This selects all <div> elements with a title attribute whose value begins with my.

What about an “attribute ends with” selector? Coming right up:

a[href$='.pdf']

This is a useful selector for locating all links that reference PDF files.

And here’s a selector for locating elements whose attributes contain arbitrary strings anywhere in the attribute value:

a[href*='jquery.com']

As we’d expect, this selector matches all <a> elements that reference the jQuery site.

Table 2.2 shows the basic CSS selectors that we can use with jQuery.

With all this knowledge in hand, head over to the Selectors Lab page, and spend some more time running experiments using selectors of various types from table 2.2.

Try to make some targeted selections like the <span> elements containing the text Hello and Goodbye (hint: you’ll need to use a combination of selectors to get the job done).

As if the power of the selectors that we’ve discussed so far isn’t enough, there are some more options that offer an even finer ability to slice and dice the page.

Table 2.2 The basic CSS selectors supported by jQuery

Selector Description

* Matches any element.

E Matches all elements with tag name E.

E F Matches all elements with tag name F that are descendants of E.

E>F Matches all elements with tag name F that are direct children of E.

E+F Matches all elements with tag name F that are immediately preceded by sibling E.

E~F Matches all elements with tag name F preceded by any sibling E.

E.C Matches all elements with tag name E with class name C. Omitting E is the same as

*.C.

E#I Matches all elements with tag name E with the id of I. Omitting E is the same as *#I.

E[A] Matches all elements with tag name E that have attribute A of any value.

E[A=V] Matches all elements with tag name E that have attribute A whose value is exactly V.

E[A^=V] Matches all elements with tag name E that have attribute A whose value starts with V.

E[A$=V] Matches all elements with tag name E that have attribute A whose value ends with V.

E[A!=V] Matches all elements with tag name E that have attribute A whose value doesn’t match the value V, or that lack attribute A completely.

E[A*=V] Matches all elements with tag name E that have attribute A whose value contains V.

27 Selecting elements for manipulation

2.1.4 Selecting by position

Sometimes, we’ll need to select elements by their position on the page or in relation to other elements. We might want to select the first link on the page, or every other paragraph, or the last list item of each list. jQuery supports mechanisms for achieving these specific selections.

For example, consider

a:first

This format of selector matches the first <a> element on the page.

What about picking every other element?

p:odd

This selector matches every odd paragraph element. As we might expect, we can also specify that evenly ordered elements be selected with

p:even

Another form,

ul li:last-child

chooses the last child of parent elements. In this example, the last <li> child of each

<ul> element is matched.

There are a whole slew of these selectors, some defined by CSS, others specific to jQuery, and they can provide surprisingly elegant solutions to sometimes tough prob-lems. The CSS specification refers to these types of selectors as pseudo-classes, but jQuery has adopted the crisper term filters, because each of these selectors filter a base selector. These filter selectors are easy to spot, as they all begin with the colon (:) character. And remember, if you omit any base selector, it defaults to *.

See table 2.3 for a list of these positional filters (which the jQuery documentation terms the basic and child filters).

Table 2.3 The positional filter selectors supported by jQuery

Selector Description

:first Matches the first match within the context. li a:first returns the first link that’s a descendant of a list item.

:last Matches the last match within the context. li a:last returns the last link that’s a descendant of a list item.

:first-child Matches the first child element within the context. li:first-child returns the first list item of each list.

:last-child Matches the last child element within the context. li:last-child

:last-child Matches the last child element within the context. li:last-child

在文檔中 IN ACTIONSECOND EDITION (頁 51-88)

相關文件