jQuery: simple selections

Although JavaScript is very handy for client-side manipulation of web pages, it suffers from at least two serious drawbacks. First, it can take a lot of code to do relatively simple things (like finding a particular element within a web page). Second, different browsers (particularly Internet Explorer) often require different code to do the same thing, so writing a web page that will always behave the same in every browser can be a major headache.

jQuery solves many of these problems. It is a JavaScript API which defines a large number of functions that both reduces the amount of code needed and eliminates many of the cross-browser problems.

At the core of jQuery (as you might guess from its name) is its ability to search the web document in a myriad of ways. (It can, of course, do a lot of other things, but more on that later.) We’ll have a look at some of these search techniques here.

First, we need to draw an important distinction between the two ways a jQuery function can return its result. Most functions return a wrapped set, which is a set of page elements contained within a JavaScript data structure. It’s a set, since there are no duplicated elements within it, even if the search string could match the same element in more than one way. Some jQuery functions will return bare elements, but we won’t be concerned with any of those in this post.

Second, most jQuery functions are called from a wrapped set, do something to that set, and then return another wrapped set. Sometimes, the second set is the same as the first one (although with some modifications to its elements), but sometimes (as with a filter) the second set is a different set than the original, as it may contain different, or more or fewer, elements. Again, we won’t be worried about this much here, since we’re going to consider mostly just a single function that searches the page for specific elements. What we do with those elements is the subject of future posts.

The format for a query in jQuery is $(<query string>), where <query string> is a string that tells the function what to look for. If you know how to use cascading style sheets (CSS), you’ll be happy to hear that most of the CSS selector strings also apply in jQuery selectors. (If you’re not familiar with CSS, as I have to admit I wasn’t when I started looking at jQuery, then this is all new, but never mind.)

In order to try out some jQuery selectors, we need a page for it to work on. Here’s the body of a web page that has a few basic tags in it:

  <h2>jQuery Selectors</h2>
      <th colspan="2">Comic Summary</th>
      <td colspan="2">
        Which is best?<br />
        <label> <input type="radio" name="dcMarvel" /> DC</label>
        <label> <input type="radio" name="dcMarvel" /> Marvel</label>
      <td colspan="2">
      What are your favourites?
          <li><label><input type="checkbox" />Batman</label></li>
          <li><label><input type="checkbox" />Superboy</label></li>
          <li><label><input type="checkbox" />Fantastic Four</label></li>
          <li><input type="checkbox" />Iron Man</li>
          <li><input type="checkbox" />Incredible Hulk</li>
          <li><input type="checkbox" />Green Lantern</li>
      <td colspan="2">
        <input type="text" id="jqtest" /></td>

This produces the following page:

For reference, this page has the simple style (specified in a CSS file):

body {

Now, suppose we want to select all <li> tags. In this case, the jQuery call is simply $(‘li’). If you want test this out, you can create your own HTML file and put the above body into it, then add the following head section (before the body, of course):

  <link href="Content/jQueryDemo.css" rel="stylesheet" />
  <script src="Scripts/jquery-1.8.2.js"></script>
    $(function () {
        function (event) {
          if (event.keyCode === 13) {
              backgroundColor: 'lightgray',
              border: 'none'
              backgroundColor: 'palegreen',
              border: '1pt solid darkgreen'

This assumes that you’ve got your CSS file in Content/jQueryDemo.css and that the jquery library is in Scripts/jquery-1.8.2.js. If you have a different version of jQuery or put your files in different places, you’ll need to modify those 2 lines in the header. If you’re using Visual Studio,  you can include jQuery as described in the last post.

As for the script in the header, don’t worry about it for now. Just be assured that when you type a query string into the text box and hit return, those page elements that you’ve selected will be highlighted in green.

Also, if you’re running a browser (such as Google Chrome) that has a console, you’ll see the selected elements printed out in the console. To activate Chrome’s console, right click on the page and select ‘Inspect element’, then click the Console tab. This is well worth doing, since not all of the selected elements get highlighted, and it’s reassuring to see that these elements have in fact been selected.

If you’ve got this page running, try typing li into the text box and hitting return. You should see this:


The 6 li elements have been highlighted. The reason that the top 3 don’t have their text highlighted is that these checkboxes are defined using the <label> tag, while the bottom 3 have a bare checkbox with some text after it. The label is a separate element that sits on top of the list, so it doesn’t get selected. Try typing label into the box and you’ll see just the top 3 checkboxes lit up, along with the 2 radio buttons.

If you want to select both li and label elements, enter li, label. That is, a comma separated list will select all elements that match any term in the list.

Although this is fairly simple, the results are global, in that you’re selecting all tags in the entire page. Suppose you wanted to select only those inputs that are inside labels. This time, you can type in label input (without a comma). (In this case, the display won’t show any items lit up, presumably because the label overwrites the input that it contains, but if you look in the console, you’ll see that the two radio buttons and top 3 checkboxes are selected.)

This form of list first selects the left-most tags (labels here) then selects children of those tags that satisfy the second condition. We could string together more tags if we have a deeper nesting on the page. Note that the input doesn’t have to be the immediate child of the label; if a label contains an input as its descendant at any point it will be selected.

If you want to restrict your choice to only immediate children, you can write td > label. This selects label tags that are immediate children of td tags. This will give you the 2 radio buttons, but not the top 3 checkboxes, since they are buried inside a ul and li tag. To compare, try typing td label (without the >) and this time you’ll get the top 3 checkboxes as well.

That’s about enough for a first post.


Post a comment or leave a trackback: Trackback URL.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: