Home / AJAX

Page History: How Do I Use jQuery Selectors?

Compare Page Revisions



« Older Revision - Back to Page History - Newer Revision »


Page Revision: 2010/09/04 22:46


Problem

jQuery provides a ton of power with minimal lines of code. But how do I perform those actions or bind events to specific elements on the page?

Solution

The basic concept of jQuery is to “select some elements and do something with them”. Selecting can arguably be considered the power behind the jQuery Library. Without the ability to easily select elements from the DOM I don’t think jQuery would be the powerful tool for the DOM as it is today.

What makes jQuery so easy to select elements is its selector engine, Sizzle, and it’s easy syntax, which is based on the same syntax you would use to select elements in CSS by borrowing from CSS 1-3. jQuery also adds additional pseudo selectors to enable you to narrow your selection further. You can find out more about selectors by reviewing the complete reference Selector category on jQuery API site.

There are many different types of selectors. Let look at some examples.

Element by ID

In this simple example below we see a selection of an element by its ID.

<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8 />
  <title>Select Element by ID</title>
</head>
<body>
  <p id="hello">Hello World</p>

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script> <script type="text/javascript"> //Select the element by it's ID alert($("#hello").text()); // Hello World </script> </body> </html>

jQuery uses the native JavaScript function getElementById(), for id selectors. The performance of using the native JavaScript function in this instance cannot be beat in any selector engine. The fastest way to select an element is to reference it by its id selector.

Note: Valid HTML requires that each ID be unique on the page. A page is not considered valid if there is more then one of the same ID on the page. Because of this, jQuery will only match the first element that matches that ID on the page.

It’s also important to point out that your id cannot contain the following characters:

#;&,.+*~':"!^$[]()=>|/

The characters above if not properly escaped may confuse the jQuery selector engine into thinking it is a different type of selector. For example the character (:) if used in the name of an id may confuse jQuery to think that a filter selector is supposed to be applied (we’ll going into more detail about filter selectors later).

To escape the character, place two backslashes in front of the character to escape it.

$(“#some:id”) -> $(“#some\\:id”)

For more tricks on dealing with special characters take a look at this FAQ on the jQuery Documentation site. You can also review the id selector on the jQuery API site.

Elements by class

In this simple example we will select all elements on the page that have the specified class name.

<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8 />
  <title>Select Element by class selector</title>
</head>
<body>
  <p id="hello">
        <span class="helloworld">Hello</span> <span class="helloworld">World</span>
  </p>

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script> <script type="text/javascript"> //Select the element by it's classname alert($(".helloworld").text()); // HelloWorld alert($(".helloworld").length); // 2 </script> </body> </html>

The selector, in the example, matched both the span elements that contained the words ‘Hello’ and ‘World’ and combined them into one result ‘HelloWorld’. I’ve also shown how many matches that the selection made by using the length property; in this case it was 2 matches.

jQuery will use the native JavaScript function GetElementsByClassName(), if the browser supports it, instead of the Sizzle selector engine as the languages native functions are always faster. You can review class selectors on the jQuery API site.

Elements by Attribute

In this simple example we will select all elements that have an attribute with the specified value.

<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8 />
  <title>Select Element by Attribute</title>
</head>
<body>
  <form>
    First Name: <input type="text" name="first_name" value="Ralph" /> 
    <br /><br />
    Last Name: <input type="text" name="last_name" value="Whitbeck" /> 
    <br /><br />
  </form>

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script> <script type="text/javascript"> //Select the element by attribute alert($("input[name=first_name]").val()); // Ralph </script> </body> </html>

The selector starts by matching all the ‘input’ elements then narrows the matched set down to the elements that have an attribute of ‘name’ that also has the value of ‘first_name’. We could of done something like this as well $(“inputname!=last_name”); which says match all input elements that do not have the attribute name with a value of ‘last_name’.

You can review the different types of Attribute selectors on the jQuery API site.

Elements by Hierarchy CSS selector

There are various types of CSS selectors that jQuery will support. These selectors will allow you refine your selection down to the elements that you are trying to get at.

Descendent Selector (“parent child”) – selects all descendent child elements of the parent. A descendant of an element could be a child, grandchild, great-grandchild, and so on, of that element.

With this HTML:
<ul>
	<li><a href="http://jquerymobile.com">jQuery Mobile</a></li>
</ul>
<div>
	<ul>
		<li><a href="http://jquery.com">jQuery</a></li>
		<li><a href="http://jqueryui.com">jQuery UI</a></li>
	</ul>
</div>
And this jQuery:
$("div ul"); 
Will select:
<ul>
	<li><a href="http://jquery.com">jQuery</a></li>
	<li><a href="http://jqueryui.com">jQuery UI</a></li>
</ul>

Child Selector (“parent > child”) – selects all direct child elements of the parent. This type of selector as a CSS Selector is supported in most modern browsers except IE 6. But within a jQuery selector it is supported by IE6.

With this HTML:
<ul>
	<li><a href="http://jquerymobile.com">jQuery Mobile</a></li>
</ul>
<div>
	<ul>
		<li><a href="http://jquery.com">jQuery</a></li>
		<li><a href="http://jqueryui.com">jQuery UI</a></li>
	</ul>
</div>
And this jQuery:
$("li > a"); 
Will select:
<a href="http://jquerymobile.com">jQuery Mobile</a>
<a href="http://jquery.com">jQuery</a>
<a href="http://jqueryui.com">jQuery UI</a>

Next Adjacent Selector (“previous + next”)- Selects all elements that match “next” that is preceded by sibling elements that match “previous”.

Next Siblings Selector (“previous ~ siblings”)– Selects all siblings that match all “siblings” elements after the “previous” elements and they have the same parent. The difference between next adjacent and next siblings selector is the reach they have. Next siblings will select all the elements after previous where next adjacent will only select the immediate element after the previous element.

Elements by Filters

In this simple example we will use a selector filter to narrow our selected elements.

<!DOCTYPE html>
<html>
<head>
 <meta charset=utf-8 />
 <title>Select Element by Selector Filter</title>
</head>
<body>
  jQuery project sites:
  <ul>
    <li><a href="http://jquery.com">jQuery</a></li>
    <li><a href="http://jqueryui.com">jQuery UI</a></li>
    <li><a href="http://sizzlejs.com">Sizzle</a></li>
    <li><a href="http://jquery.org">jQuery Project</a></li>
  </ul>
    
 <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script>
 <script type="text/javascript">
   
//Select the element by attribute
     	alert($("a:first").attr("href")); // http://jquery.com
  </script>
</body>
</html>

There are three kinds of filter selectors that you can use, numerical or positioned filters:

:first - Matches the first item in the context
:last - Matches the last item in the context
:first-child - Matches the first child item in the context
:last-child - Matches the last child item in the context
:only-child - Returns all items that have no siblings
:nth-child(n) - Matches the nth child item in the context
:nth-child(even|odd) - Matches the even or odd children in the context
:nth-child(xn+y) - Matches the nth children based on the formula. Examples: (3x+1) Get the first element after every third child. (3x) get every third child element.
:even - Match the even children in the context
:odd - Match the odd children in the context
:eq(n) - Match the child at the nth position in the context
:gt(n) - Match the children that are greater then the nth position in the context
:lt(n) - Match the children that are lesser then the nth position in the context

Traditional CSS filters:

:checked - Matches checkbox/radio button elements in checked state :disabled - Matches disabled elements :enabled - Matches enabled elements :not(selector) - Matches elements that are not in the selection

jQuery Pseudo filters:

:animated - Matches elements that are being animated. :button - Matches button elements :checkbox - Matches checkbox elements :contains(string) - Matches elements that contain specified string (i.e. $(“p:contains(jQuery)”);) :file - Matches file input elements :has(selector) - Matches elements that have at least one of the specified matched selector. :header - Matches header elements. (i.e. h1-h6) :hidden - Matches hidden elements :image - Matches image input elements :input - Matches form elements :parent - Matches elements that have children, including text, which are not empty :password - Matches elements of type password :radio - Matches radio elements :reset - Matches reset buttons :selected - Matches option elements in selected state :submit - Matches elements of type submit :text - Matches elements of type text :visible - Matches elements that are visible

NOTE: For the :visible and :hidden pseudo filters jQuery tests for actual visibility by looking at the elements offsetHeight and offsetWidth. If these properties are set to 0 the element is considered hidden. The CSS visibility or display maybe set but it is considered visible only if the physical width and height are greater then 0.

jQuery uses the offset test successfully on all elements except TR elements. In that case jQuery uses the CSS display property to determine visibility.

Working with your selection

Length

jQuery will fail silently if there are no elements that match your selection. There maybe a time when you will want to perform some actions based on if an element is present or not in the DOM. To test for an element we use the length property to test how many elements are in the DOM.

If ($(“div”).length) {
//do something.
}

In JavaScript, 0 is considered a “falsy” value. So if the length is 0 then the if statement will fail. If it is greater then 0 then the if statement will pass.

Stacking Selectors

You can have multiple selectors at once. For instance say you wanted to perform the same actions on two different elements. You could select each element and them perform the actions against both:

$(“div”).show();
$(“p”).show();

We could stack these selections into one line of code by separating the selection with a comma just like you would in a CSS declaration.

$(“div, p”).show();

Additionally, you can stack attribute selectors as well.

$(“a[href=http://jquery.com][class=mainnav]”).show();

The same can be done with filters.

$(“a:contains(jQuery):first).show();

Performance tip

When working with the same selection many times it’s best to ‘cache’ the selection and use the ‘cached’ jQuery object of your selection instead. This will save the time of jQuery selecting the elements you want each time you want to perform an action again it.

	var $p = $(“p”);

$p.show(); $p.hide(); $p.show();

Convention is to start your cached variable of a jQuery object with a $ to denote that the variable contains a jQuery object.

We’ve performed three separate actions on the p elements that we selected but we only selected those elements once. If we didn’t cache the jQuery Object we would of initialize a new jQuery object with a collection of p elements three times.