How to Select Elements with jQuery
ost of what you’ll do in jQuery happens through selectors. For instance, you’ll frequently select a piece of a web page and then have jQuery perform an action on that piece of the page. That action could be anything from adding text, changing HTML, changing CSS or, well, just about anything you can think of!
Select an element on the web page (or the entire page itself).
Do something interesting with that element.
Okay, what you do with the element doesn’t have to be interesting, but you will do something with the selected element. That something can be anything from removing the element to adding or changing it or simply getting information from the element, like its text or current CSS styles.
jQuery selectors up close
There are three primary or basic selectors in jQuery. They’re the ones you’ll use most frequently. You can set up very complex selectors based on the structure of the page, but most often you’ll use one of these three selectors:
If you had some HTML that looked like this:
<p id="bookTitle">My Book</p>
You could access that with jQuery like this:
Now take a look at this bit of HTML:
<p class="titleClass">This is some text</p>
The jQuery selector looks like this:
If you think that these selectors look like their CSS counterparts, you’re right. Don’t worry if you weren’t thinking that; there won’t be a quiz.
In CSS, you access items by their ID with a pound sign (#) and you access classes with a single dot (.):
All you’re doing for jQuery is wrapping it in the $() construct and using some quotes too. So you get this:
The other frequently used selector grabs all the elements of a certain type. The following selector selects all <div> elements on the entire page:
There are more advanced selectors. For example, you can select by an element’s position on the page and, well, just about any combination that you can think of. But you’ll use these three most often.
One additional thing you should know about jQuery selectors is that you can filter them. This is particularly handy when it comes to working with forms and events.