CSS Selectors are patterns that match tags and attributes to the HTML markup itself. Many are fundamental to the CSS core, the
Sizzle.js engine under
$() provides extends selectors with more advanced features and capabilities.
Selectors also represent the WHERE clause of the SQL analogy, so we need to understand their capabilities and also consider that poorly written jQuery can affect browser performance.
Once you understand selectors, you understand jQuery. If you can identify the page elements you want to change, you can apply any of a diverse set of functions to it. It will be like riding a bike—once you know how, you want to go exploring.
Tags, IDs, and Classes
The sample page offers two options to locate the h1 tag. All HTML tags can be identified by name, and hierarchy can be signified within the selector. Any h1 tags within a bodynode would be returned using the following:
The other option is to use the element’s ID attribute to uniquely identify a page element. For example, you can identify a specific element referring to the ID using the # symbol:
Classes are identified with the format tag.class. The class can be identified by itself with the .coolCat dot notation. However, to aid performance in many cases, it’s recommended to precede it with the HTML tag that would have that class. This selector locates any list items with the coolCat class.
Tip ID and class selectors are case sensitive, as per the string comparisons in the SQL. Tags, however, tolerate either case.
Attributes and Operator
It’s possibly to identify elements by other attributes. A common example I use in APEX is to look in a report identified with the id p2_emps and locate any cells for the ENAME column:
This translates to the HTML typically generated for APEX classic report data columns:
The earlier example of h1#demo1 could also be written in a similar way, but classes and IDs have their own identifiers so the shortened form can be used instead:
Searching for attribute values becomes more flexible with operator extensions similar to % and _ wildcards in SQL. The tilde in the following example looks for attributes beginning with the string "DATE". As a result, the invocation of jQuery targets APEX columns such as DATE_CALLED, DATE_MODIFIED, and so forth:
Pseudo-selectors are used to identify information that is not in the document tree. A common example you may have seen is:hover, typically applied on an anchor tag in the form
Examples specific to jQuery include tr:even, to get all the even tr elements; or :contains(’wesley’), to return all those elements containing my name as text. Specific siblings such as list items in an unordered list can be identified positionally like an array:
Tip Web sites such as caniuse.com help determine why certain CSS or HTML tags are not recognized in your browser. IE has a history of lagging behind in support due to longer release cycles.