tech, tunes, and other stuff

jQuery Notes - Selectors

In order to manipulate web page elements, the element must first be selected.  jQuery provides for selecting web pages elements via jQuery objects.

There are three basic types of selectors:  IDs, classes, and elements.

Basic Selectors
CSS jQuery

John Doe


This can be anything

element Ixquick Search $(‘a’)


More advanced selectors can be made: descendent, child, adjacent, attribute


Advanced Selectors
CSS jQuery effect
$(‘#navBar a’) selects only links in the unordered list
child $(‘body > p’) selects only the p tags that are children of the body tag
adjacent $(‘h2 + div’) selects only the div tags that are directly after an h2 tag


A special set of selectors are the attribute selectors, which allow for the selection of elements based on their attribute values.


Attribute Selectors
jQuery example effect
[attribute] $(a[href]) matches all elements that have a specific type of attribute
[attribute=”value”] $(input[type=”text”]) matches a specific attribute value
[attribute^=”value”] $(a[href^=”http://”]) matches a specific value at the beginning of an attribute
[attribute$=”value”] $(a[href$=”.pdf”]) matches a specific value at the end of an attribute
[attribute*=”value”] $(a[href*=”jwallace.us”]) matches a specific value anywhere in the attribute


Selections can be filtered in jQuery too:


Selector Filters
jQuery example effect
:even $(‘tr:even’) matches every even row in a table
:odd $(‘tr:odd’) matches every odd row in a table
:first $(‘p:first’) matches the first paragraph on a page
:last $(‘p:last’) matches the last paragraph on a page
:not $(‘a:not(.header)’) matches all anchors not in a the .header class
:has $(‘li:has(a)’) matches all list elements that have an anchor tag
:contains $(‘p:contains(ABACAB)’) matches all paragraphs that contain the text “ABACAB”
:hidden $(‘div:hidden’) matches all hidden div elements
:visible $(‘div:visible’) matches all visible div elements


Selection Chaining

It is possible to chain several selectors together for a combined effect.  For example, to select an element with an ID of popup, you could do the following:

$(‘#popup’).width(300).height(300).text(‘hello world’).fadeIn(1000);

This page is a summary of information found in: JavaScript and jQuery: The Missing Manual, pp129-137