Using elements, ID's and classes
The #id selectorA very common selector type is the ID based, which we saw in the "Hello, world" example. It uses the ID attribute of a HTML tag to locate the desired element. An ID should be unique, so you should only use this selector when you wish to locate a single, unique element. To locate an element with a specific ID, write a hash character, followed by the ID of the element you wish to locate, like this:
$("#divTest")An example of it in use:
The .class selectorElements with a specific class can be matched by writing a . character followed by the name of the class. Here is an example:
The element selectorYou can also match elements based on their tag names. For instance, you can match all links on a page like this:
Or all div tags like this:
If you use a multi-element selector, like the class selector we used in the previous example, and we know that we're looking for elements of a specific type, it's good practice to specify the element type before the selector. Not only is it more precise, it's also faster for jQuery to process, resulting in more responsive sites. Here is a re-written version of the previous example, where we use this method:
$("span.bold").css("font-weight", "bold");This will match all span elements with "bold" as the class. Of course, it can be used with ID's and pretty much all of the other selectors as well.
Selectors can do much more for you though. Read on for more cool examples.