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:25


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.