Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

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!

The basic flow for JavaScript programming with jQuery is this:

  1. Select an element on the web page (or the entire page itself).

  2. 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:

  • By class

  • By ID

  • By element

If you had some HTML that looked like this:

<p id="bookTitle">My Book</p>

You could access that with jQuery like this:

$("#bookTitle")

It's important to note that things in jQuery (and JavaScript) are case sensitive. So booktitle is not the same as BOOKTITLE and not the same as bookTitle. It doesn't matter what case you use, as long as it matches between the HTML and the JavaScript and jQuery.

Now take a look at this bit of HTML:

<p class="titleClass">This is some text</p>

The jQuery selector looks like this:

$(".titleClass")

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 (.):

#bookTitle
.titleClass

All you're doing for jQuery is wrapping it in the $() construct and using some quotes too. So you get this:

$("#bookTitle")
$(".titleClass")

The other frequently used selector grabs all the elements of a certain type. The following selector selects all <div> elements on the entire page:

$("div")

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.

jQuery filtering

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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.