Selectors are required in every statement using jQuery. The point of a selector is to select the element on which to perform an action. Selectors can select almost anything you want, from CSS styles to HTML elements. Enough talking, let’s look at some examples.
Common Selectors
- $(“p”) – selects all of the <p> elements
- $("[href]") – selects all of the elements with an href attribute
- $(":textbox") – selects all of the <textbox> elements
- $(“#someId”) – selects all of the elements where the id = “someId”
- $(“.someClass”) – selects all of the elements where the class = “someClass”
- $(“p#someId”) – selects all of the <p> elements where the id = “someId”
- $(“p.someClass”) – selects all of the <p> elements where the class = “someClass”
- $("p:first") – selects the first <p>
- $("ul li:first") – selects the first <li> element of the <ul>
- $(":even") – selects all of the even elements (useful in tables, lists, etc.)
- $(":odd") – selects all of the odd elements (useful in tables, lists, etc.)
These are just a few of the selectors that jQuery contains. For a full list of selectors, visit jQuery Selectors.
As you can see with the selectors above, it is always a good idea to plan your HTML and CSS to use jQuery. It is possible for you to edit your styles and elements after the fact, but it is not ideal. Try implementing ids and classes into your HTML and CSS before you start with your jQuery. You will thank yourself for it.