How to Select Elements with jQuery in CSS3 - dummies

How to Select Elements with jQuery in CSS3

By John Paul Mueller

You can use jQuery to perform a vast array of object selections in your CSS3 application, but for the most part, you use the basic selectors. You can read more about them at jQuery. Here’s a list of basic selectors that you commonly use:

  • All selector (“*”): Selects all the elements in the document.

  • Object selector (object): Selects the specific object types. The most commonly used object is document.

  • Class selector (“.class”): Selects a specific class as specified by the class attribute for an element. This selector always appears within quotes and is preceded by a period.

  • Element selector (“element”): Accesses all the elements with a particular tag name, such as p for the <p> tag. This selector always appears within quotes.

  • ID selector (“#id”): Chooses a specific element with the id attribute value specified. This selector always appears within quotes and is preceded by a pound sign (#).

  • Multiple selector (“selector1, selector2, selectorN”): Selects each of the elements specified in the comma delimited list.

One of the more commonly used selectors is the element selector. After you select an element, you can change it in a number of ways. For example, you might choose to change the text associated with that element in some way (later examples will show all sorts of other ways to manipulate output).

The following example shows how to select elements and modify their associated text. (You can find complete code for this example in the Chapter 06jQuery folder of the downloadable code as SelectingElements.html.)

<!DOCTYPE html>
 <title>Selecting Elements</title>
 <script type="text/javascript">
 $("h1").text("A Sample Header")
 $("p").text("This is a sample paragraph.")

The example begins with simple <h1> and <p> tags that don’t contain any text. If you displayed this page without the script, you’d see a blank page. However, with the script in place, the page now contains information. It’s also possible to use the text() method to obtain the current value of an object of any sort (assuming the object actually contains text).