A Beginner’s Guide to jQuery’s Selectors
We talk a lot about event methods on this site, but not so much about jQuery's selectors. Selectors in jQuery are actually similar in a lot of ways to selectors in CSS. For example, when you want to select an ID, you precede it with the "#" symbol, and when you want to select a class, you precede it with the "." symbol, only the syntax for doing so is quite different.
In jQuery, when you want to select an element (for the purposes of this example, let's say you're selecting an element with the ID of "main"), your selector will need to look like this:
So like CSS, you use the "#" symbol to indicate that it's a class you're selecting, but unlike CSS, the selection text all needs to go in within quotation marks, surrounded by parentheses, and preceded by the "$" jQuery symbol. It's important to remember using both the parentheses and the quotation marks when selecting elements. The quotation marks need to be used when you're selecting any HTML element, regardless if you're selecting it by the class or ID name. The only time you don't need to use quotation marks is if you're selecting a jQuery keyword, like window, for example. You'll still need the parentheses though.
Selecting window in jQuery would look like this:
There are many other ways that you can select items, and this is where jQuery selectors continue to resemble those of CSS. For example, just like CSS, jQuery also has a universal selector, and it happens to also be the * asterisk symbol. To select all of the elements on a page using jQuery, use the following selector:
You can also use pseudo-selectors when using jQuery to select elements, like :first, :last, :odd, or :even, :first-child, :last-child, :only-child, :nth-of-type(n), etc. So for example, if you want to select only the first element that appears on a page of a type (let's say the first element of an h2 tag), you could use the following selector:
Or if you wanted to select and odd-number occurring element of a tag type (so for example, the first, third, fifth, etc occurrence of a p tag), you could use this selector:
You can also employ the selector symbols, >, +, and ~, which are used to indicate direct children, elements that are next to each other, and sibling elements, respectively. So to select any p elements that are the direct children of a div element, you can use the following jQuery selector:
$("div > p")
If you're familiar with CSS, then you know that most of these selector rules and relationships also apply in the styling language. If you're a pro at CSS but only just learning jQuery, you'll find that when it comes to selectors, there are actually many similarities between the languages. When in doubt, you should always look up the answer, but if a selector works in CSS, you should feel pretty confident in knowing that the chances it also works in jQuery are very high.