Bibliographic Information

Pro PHP and jQuery

by Jason Lengstrof, ISBN 1430228474 / 978-1430228479
2010, Apress

SUPER FUN - TRY OUT THESE WITH FIREBUG.

1.4.2. Selecting DOM Elements Using CSS Syntax

Everything in jQuery revolves around its incredibly powerful selector engine. The rest of this chapter teaches you the different methods with which you can select elements from the Document Object Model (DOM) using jQuery.
NOTE
The DOM is a collection of objects and nodes that make up HTML, XHTML, and XML documents. It is platform-and language-independent—this essentially means that developers can use a variety of programming languages (such as JavaScript) to access and modify DOM information on multiple platforms (such as web browsers) without compatibility issues.
One of the strongest and most alluring features of jQuery is the ease with which a developer is able to select elements within the DOM. The use of pseudo-CSS selectors[] adds an incredible level of power to jQuery. Pseudo-CSS allows a developer to target specific instances of elements in his HTML. This is especially helpful to anyone with prior experience with CSS due to the nearly identical syntax. Essentially, using the same CSS syntax you would use to set up style rules, you're able to select elements in the following ways:
  • Basic selectors
  • Hierarchy selectors
  • Filters
    • Basic filters
    • Content filters
    • Visibility filters
    • Attribute filters
    • Child filters
  • Form filters
1.4.2.1. Basic Selectors
The basic selectors allow developers to select elements by tag type, class name, ID, or any combination thereof. While viewing http://localhost/testing/, launch the Firebug dialog, and click the Console tab (see Figure 1-4). If the Console panel is disabled, click the Console tab, and select Enabled. You will be using this console for all examples in this chapter.
NOTE
If you're familiar with CSS, you will be able to skim this section, because the selectors behave the same as their CSS counterparts.
1.4.2.1.1. Selecting Elements by Tag Type
To select an element by tag type, simply use the name of the tag (such as p, div, or span) as your selector:
element
To select all paragraph (

) tags in our test document, enter the following snippet at the bottom of the console:
$("p");
Press Enter and the code will execute. The following results will be displayed in the console (see Figure 1-4):
>>> $("p");
[ p, p.foo, p, p#bar ]
The first line shows the command that was executed, and the second line shows what was returned from the code. There are four paragraph tags in our test document: two without class or ID attributes, one with a class foo, and one with an ID bar (you'll learn about this syntax in the next sections). When we pass the tag name to the jQuery function, all instances are found and added to the jQuery object.
Figure 1-4. The Firebug console after executing a command

1.4.2.1.2. Selecting Tags by Class Name
Just as quickly as you can select by tag type, you can select elements by their assigned class or classes. The syntax for this is the use the class name preceded by a period (.):
.class
Select all the elements with the class foo by executing the following snippet in the console:
$(".foo");
After execution, the following will show up in the console:
>>> $(".foo");
[ p.foo, span.foo ]
Both a paragraph tag and a span are returned, since they both have the class foo.
1.4.2.1.3. Selecting Elements by ID
To select an element by its id attribute, the CSS syntax of the id preceded by a hash sign (#) is used.
#id
Match all elements with an ID of bar with the following:
$("#bar");
Only one paragraph in our document has an id of "bar", as we see in the result:
>>> $("#bar");
[ p#bar ]
1.4.2.1.4. Combining Selectors for More-Precise Selection
In some situations, it may be necessary to isolate only certain tags that correspond to a class, which is easy to do by combining tag type and class in your selector.
Enter the following in the console to select only paragraph tags with the class foo:
$("p.foo");
The results in the console confirm that the span was ignored, even though it has the class foo:
>>> $("p.foo");
[p.foo]
1.4.2.1.5. Using Multiple Selectors
In the event that you need to access multiple elements, multiple selectors can be used to access all of those elements at once. For instance, if you wanted to select any paragraph tag with a class of foo or any element with an ID of bar, you would use the following:
$("p.foo,#bar");
This returns elements that match at least one selector specified in |the string:
>>> $("p.foo,#bar");
[ p.foo, p#bar ]
1.4.2.2. Hierarchy Selectors
Sometimes, it's not enough to be able to select by element, class, or ID. There are points at which you'll need to access elements contained within, next to, or after another element, such as removing an active class from all menu items except the one that was just clicked, grabbing all the list items out of the selected unordered list, or changing attributes on the wrapper element when a form item is selected.
1.4.2.2.1. Selecting Descendant Elements
Selecting descendant elements, which are elements contained within other elements, is done using the ancestor selector followed by a space and the descendant selector.
ancestor descendent
To select descendant spans in your test document, execute the following command in the Firebug console:
$("body span");
This will find all spans contained within the body tag () of the document, even though the spans are also inside paragraph tags.
>>> $("body span");
[ span, span.foo ]
1.4.2.2.2. Selecting Child Elements
Child elements are a more-specific style of descendant selector. Only the very next level of element is considered for matching. To select a child element, use the parent element followed by a greater than (>) symbol, followed by the child element to match:
parent>child
In your test file, try to select any spans that are child elements of the body element by entering the following command in the console:
$("body>span");
Because there are no spans directly contained within the body element, the console will output the following:
>>> $("body>span");
[ ]
Next, filter all span elements that are direct children of a paragraph element:
$("p>span");
The resulting output looks like this:
>>> $("p>span");
[ span, span.foo ]
1.4.2.2.3. Selecting Next Elements
Occasionally in a script, you'll need to select the next element in the DOM. This is accomplished by providing an identifier for the starting element (any selector pattern works here), followed by a plus sign (+), followed by the selector to match the next instance of:
start+next
Try this in the console by typing the following command:
$(".foo+p");
There is only one element with the class foo, so only one paragraph element is returned:
>>> $('.foo+p');
[ p ]
Next, use a more general query, and select the next paragraph element after any paragraph element:
$('p+p');
There are four paragraphs in our markup, and all of them but the last have a next paragraph, so the console will display three elements in the result:
>>> $('p+p');
[ p.foo, p, p#bar ]
This result set is the second, third, and fourth paragraphs from the HTML markup.
1.4.2.2.4. Selecting Sibling Elements
Sibling elements are any elements contained within the same element. Selecting sibling elements works similarly to selecting next elements, except the sibling selector will match all sibling elements after the starting element, rather than just the next one.
To select sibling elements, use the starting element selector, followed by an equivalency sign (~), and the selector to match sibling elements with:
start~siblings
To match all siblings after the paragraph with class foo, execute the following command in the console:
$(".foo~p");
The result set will look like the following:
>>> $(".foo~p");
[ p, p#bar ]

SUPER FUN - TRY OUT THESE WITH FIREBUG. Cont.

1.4.2.3. Basic Filters
Filters are another very powerful method of accessing elements in the DOM. Instead of relying on element types, classes, or IDs, you're able to find elements based on their position, current state, or other variables.
The basic syntax of a filter is a colon (:) followed by the filter name:
:filter
In some filters, a parameter can be passed in parentheses:
:filter(parameter)
The most common and useful filters are covered in the next few sections.
NOTE
Not all available filters are covered here for the sake of getting into actual development quickly. For a complete listing of available filters, see the jQuery documentation.
1.4.2.3.1. Selecting First or Last Elements
One of the most common uses of filters is to determine if an element is the first or last element in a set. With filters, finding the first or last element is incredibly simple; just append the filter :first or :last to any selector:
$("p:last");
This returns the following when executed in the console:
>>> $("p:last");
[ p#bar ]
1.4.2.3.2. Selecting Elements that Do Not Match a Selector
If you need to find all elements that don't match a selector, the :not() filter is the easiest way to go about it. Append this filter to your selector along with a selector as its parameter, and the results set will return any elements that match the original selector, but not the selector passed as a parameter to :not().
For example:
$("p:not(.foo)");
Will return the following result set:
>>> $("p:not(.foo)");
[ p, p, p#bar ]
1.4.2.3.3. Selecting Even or Odd Elements
Similar to :first and :last, the :even and :odd filters are syntactically simple and return exactly what you might expect: the even or odd elements from a result set, respectively.
$("p:odd");
Executing the preceding line in the console will result in the following output:
>>> $("p:odd");
[ p.foo, p#bar ]
1.4.2.3.4. Selecting Elements by Index
In the event that you need to grab a particular element by its index, the :eq() filter allows you to specify which element is needed by passing an index as the filter's parameter:
$("p:eq(3)");
This outputs the following:
>>> $("p:eq(3)");,
[ p#bar ]
NOTE
An element's index refers to its position among other elements in the set. Counting in programming starts a zero (0), so the first element is at index 0; the second is at index 1, and so on.
1.4.2.4. Content Filters
Filters are also available to select elements based on their content. These can range from containing certain text to surrounding a given element.
1.4.2.4.1. Selecting Elements That Contain Certain Text
To select only elements that contain certain text, use the :contains() filter, where the text to be matched is passed as a parameter to the filter:
$("p:contains(Another)");
When executed in the console, the preceding line will return the following:
>>> $("p:contains(Another)");
[ p.foo ]
NOTE
The :contains() filter is case sensitive, meaning capitalization matters for matching text. A case-insensitive version of the filter has been added to the comments of the :contains() entry on the API documentation by a member of the development community. For more on this filter, see http://api.jquery.com/contains-selector.
1.4.2.4.2. Selecting Elements That Contain a Certain Element
If you need to select only elements that contain another element, you would use the :has() filter. This works similarly to :contains(), except it accepts an element name instead of a string of text:
$("p:has(span)");
When executed in the console, this outputs the following:
>>> $("p:has(span)");
[ p, p#bar ]
Only paragraphs containing span elements are returned.
1.4.2.4.3. Selecting Elements That Are Empty
To find elements that are empty (meaning the element contains neither text nor any other elements), the :empty filter comes into play.
In the HTML example you're using, the only empty elements are not visible. Select them by looking for any empty element:
$(":empty");
This outputs the following:
>>> $(":empty");
[ script jsapi, script jquery.min.js, div#_firebugConsole ]
Both the second script tag and the div are dynamically generated. The script tag comes from jQuery being loaded by the Google JSAPI, and the div comes from Firebug.
1.4.2.4.4. Selecting Elements That Are Parents
The opposite of :empty, :parent will only match elements that contain children, which can be either other elements, text, or both.
Select all paragraphs that are parents using the following:
$("p:parent");
Because all paragraphs in your sample HTML document contain text (and other elements in some cases), all paragraphs are returned in the result set:
>>> $("p:parent");
[ p, p.foo, p, p#bar ]
1.4.2.5. Visibility Filters
Visibility filters, :hidden and :visible, will select elements that are, respectively, hidden and visible. Select all visible paragraphs like so:
$("p:visible");
Because none of the elements in your HTML example are currently hidden, this returns the following result set:
>>> $("p:visible");
[ p, p.foo, p, p#bar ]
1.4.2.6. Attribute Filters
Element attributes are also a great way to select elements. An attribute is anything in the element that further defines it (this includes the class, href, ID, or title attributes). For the following examples, you'll be accessing the class attribute.
NOTE
Please bear in mind that it is faster (and better practice) to use ID (#id) and class (.class) selectors in production scripts whenever possible; the examples below are just to demonstrate the capabilities of the filter.
1.4.2.6.1. Selecting Elements That Match an Attribute and Value
To match elements that have a given attribute and value, enclose the attribute-value pair in square brackets ([]):
[attribute=value]
To select all elements with a class attribute of foo, execute the following in the console:
$("[class=foo]");
This returns the following:
>>> $("[class=foo]");
[ p.foo, span.foo ]
1.4.2.6.2. Selecting Elements That Don't Have the Attribute or Don't Match the Attribute Value
Inversely, to select elements that do not match an attribute-value pair, insert an exclamation point (!) before the equals sign between the attribute and value:
[attribute!=value]
Select all paragraphs without the class foo by running the following command:
$("p[class!=foo]");
This results in the following:
>>> $("p[class!=foo]");
[ p, p, p#bar ]
1.4.2.7. Child Filters
Child filters add an alternative to the use of :even, :odd, or :eq(). The main difference is that this set of filters starts indexing at 1 instead of 0 (like :eq() does).
1.4.2.7.1. Selecting Even or Odd Parameters or Parameters by Index or Equation
One of the more versatile filters, :nth-child() provides four different options to pass as a parameter when selecting elements: even, odd, index, or an equation.
Like other child filters, this one starts indexing at 1 instead of 0, so the first element is at index 1, the second element at 2, and so on.
Using :odd, the result set contained the paragraphs with a class of foo and an ID of foo; select odd paragraphs using :nth-child() to see the difference in how the filters handle by executing the following command:
$("p:nth-child(odd)");
The results display as follows in the console:
>>> $("p:nth-child(odd)");
[ p, p ]
Though this output may seem strange, the mismatched results are a product of the difference in how the elements index.
1.4.2.7.2. Selecting First or Last Child Elements
While very similar to :first and :last, :first-child and :last-child differ in that the returned element set can contain more than one match. For instance, to find the last span that is a child of a paragraph element, you might use the following:
$("p span:last");
which returns the following in the console:
>>> $("p span:last");
[ span.foo ]
However, if you needed to find every span that was the last child of a paragraph element, you would use :last-child instead:
$("p span:last-child");
This uses each parent as a reference instead of the DOM as a whole, so the results are different:
>>> $("p span:last-child");
[ span, span.foo ]
1.4.2.8. Form Filters
Forms are a huge part of web sites these days, and their major role inspired a set of filters specifically geared toward forms.
Because your HTML example does not have any form elements in it, you'll need to append the file with some new markup for the following examples.
In index.html, add the following HTML between the last paragraph tag and the first script tag:
Code View: Scroll / Show All
<form action="#" method="post">
<fieldset>
<legend>Sign Up Form</legend>
<label for="name">Name</label><br />
<input name="name" id="name" type="text" /><br />
<label for="password">Password</label><br />
<input name="password" id="password"
type="password" /><br /><br />
<label>
<input type="radio" name="loc" />
I'm on my computer
</label><br />
<label>
<input type="radio" name="loc" checked="checked" />
I'm on a shared computer
</label><br /><br />
<input type="submit" value="Log In" /><br />
<label>
<input type="checkbox" name="notify"
disabled="true" />
Keep me signed in on this computer
</label><br />
</fieldset>
</form>
After saving, reload the page in your browser at http://localhost/testing/ to see the form for testing (see Figure 1-5).
Figure 1-5. The form as it appears after editing index.html

1.4.2.8.1. Matching by Form Element Type
The most common form-specific filters simply match form element types. The available filters are :button, :checkbox, :file, :image, :input, :password, :radio, :submit, and :text.
To select all radio inputs, use the following code:
$("input:radio");
This outputs the following in the console:
>>> $("input:radio");
[ input on, input on ]
These filters are particularly useful because all of the provided types are input elements, so matching certain types of inputs only without these filters would be a little more difficult.
1.4.2.8.2. Selecting Only Enabled or Disabled Form Elements
Additionally, filters to select enabled or disabled form elements are available using :enabled and :disabled. To select all disabled form elements, use the following code:
$(":disabled");
This outputs the following in the console:
>>> $(":disabled");
[ input on ]
The "Keep me signed in on this computer" check box is disabled, and therefore returned, by the :disabled filter.
1.4.2.8.3. Selecting Checked or Selected Form Elements
Radio and check box inputs have a checked state, and select inputs have a selected state. Filters are provided to retrieve the form elements that are in either state using :checked or :selected, respectively.
To select the currently checked radio button in your HTML example, execute the following code in the console:
$(":checked");
This returns the radio input that is currently selected in the console:
>>> $(":checked");
[ input on ]

These are notes I made after reading this book. See more book notes

Just to let you know, this page was last updated Monday, Mar 18 24