jQuery Selectors (Basic and Basic Filters)
In Part 1 of this series you were introduced with jQuery with a simple
example. Now let's move ahead and learn one of the most powerful features of
jQuery - Selectors.
What are Selectors?
While working with client side script you often need to perform specific
tasks to certain elements. For example, you may want to read value of a textbox
whose ID is TextBox1 or you may want to display all the rows of a table in red
color that contain a negative value. jQuery selectors allow you to match HTML
elements against certain criteria and select them for further processing. jQuery
builds on the selectors provided by CSS 3.0 and adds some of its own. jQuery
selectors can be grouped into the following eight categories:
- Basic
- Basic Filter
- Attribute
- Child Filters
- Content Filters
- Form
- Hierarchy
- Visibility filters
Let's begin with the basic selectors.
Understanding Basic Selectors
Basic selectors are the elementary selectors that are widely used for
selecting HTML elements. Basic selectors together allow you to :
- Select all elements from a page
- Select an element with a unique ID
- Select elements with a specific CSS class attached to them
- Select elements whose HTML tag name matches the specified one
- Select elements based on the combination of above options
Out of the above basic selectors you have already used ID selector in the
previous part. So, I will focus more on the remaining ones.
Selecting all elements from a page
The selector that allows you select all the elements from a web page is
called as "all selector" and is represented by *. All selector returns all the
HTML elements from the page including <head> elements. Consider a case where you
have a web form with several server controls on it. You want end user to control
the font family of all of the HTML elements. See the Figure below that
illustrates such a web form:
The web form consists of two DropDownList controls, a GridView control and
few Label controls. The GridView is bound with a SQL Data Source control and
displays data from the Employees table of Northwind database. The DropDownLists
at the top allow you to choose font-family and font size respectively. Once
selected it gets applied to all the elements existing on the page. The jQuery
code that does this is shown below:
$(document).ready(function() {
$("#DropDownList1").change(
function() {
var fontname = $("#DropDownList1").val();
$("*").css("font-family", fontname);
}
),
$("#DropDownList2").change(
function() {
var fontsize = $("#DropDownList2").val();
$("*").css("font-size", fontsize);
}
)
}
)
The code shown above adds a change event handler for both the DropDownList
controls. Notice the use of #<ID> to select a DOM element with a unique ID. The
change event handler of DropDownList1 uses the * selector and applies a CSS
style to it using css() function. The first parameter to the css() function is
the CSS style property to change (font-family in this case) and the second
parameter is its value. On the same lines DropDownList2 change event handler
sets the font-size for all the elements. If you run the web form and try
different values from the DropDownList controls you will find that every element
from the web form assumes the new font-family and font-size.
Select elements with a specific CSS class attached to them
The CSS selector allows you to select elements that have certain CSS class or
classes attached. Consider the following example.
The above web form consists of two GridView controls and display records from
Employee table of Northwind database. The look and feel of GridView rows is
defined by the following CSS classes :
.HeaderStyle
{
background-color:Black;
color:White;
padding:5pt;
}
.RowStyle1
{
background-color:Blue;
color:White;
}
.AlternateRowStyle1
{
background-color:Aqua;
color:Navy;
}
.RowStyle2
{
background-color:Yellow;
color:Red;
}
.AlternateRowStyle2
{
background-color:Maroon;
color:White;
}
As you might have guessed, RowXXXX classes are applied to rows and
AlternateXXXX classes are applied to alternating rows of the GirdViews. The
HeaderStyle class controls how GridView header row is displayed. The RowXXXX and
AlternateXXXX classes are attached to GridView1 as follows :
<HeaderStyle CssClass="HeaderStyle" />
<AlternatingRowStyle CssClass="AlternateRowStyle1" />
<RowStyle CssClass="RowStyle1" />
GridView2 has the other set of classes attached in similar fashion.
Now, assume that you want end user to change the look and feel of GridView
controls dynamically using jQuery. To do this the web form has provision at the
top where the user can select a CSS class from the DropDownList and then replace
that class with different look and feel. The jQuery code that does this job is
shown below :
$(document).ready
(
function() {
$("#Button1").click
(
function(event) {
var style = $("#DropDownList1").val();
$("." + style).css("background-color", $("#TextBox1").val());
$("." + style).css("color", $("#TextBox2").val());
event.preventDefault();
}
)
}
)
Look at the code marked in bold letters. It uses CSS selector to select all
the HTML elements that have the specified CSS class applied. The CSS class name
must be mentioned with . and so we prepend it to the DropDownList value. The
code then uses css() function to set new background color and text color as
entered in the textboxes.
The following figure shows a sample run of the web form. Notice how GridView1
is now being displayed with different coloring.
You can also specify multiple CSS classes in the CSS selector as shown below:
$(".class1.class2")
Select elements whose HTML tag name matches the specified one
The element selector is a commonly used selector and allows you to get hold
of all the HTML elements with a specified tag name. For example, see the web
form below :
There is a GridView control displaying Employee records. The DropDownList at
the top allows you to control text alignment of GridView columns. Moreover, when
you hover the mouse pointer over a row it is displayed in highlighted color. If
you click on that row an alert is displayed informing you which employee ID you
clicked. The jQuery code that does the trick is shown below :
$(document).ready
(
function() {
$("#DropDownList1").change
(
function() {
$("td").css("text-align", $("#DropDownList1").val());
}
)
,
$("#GridView1 tbody tr").hover(function() {
$(this).addClass('HoverRow');
},function() {
$(this).removeClass('HoverRow');
}).click(function() {
alert("You selected Employee ID :" + $("td:first", this).text());
});
}
)
The first line in bold letters uses element selector to fetch all the <td>
elements. It then sets text-alignment of those table cells to a value as
selected in the DropDownList. More interesting part, the hovering effect, is
accomplished with the next block of code.
Look at the element selector here. It is actually a combination of ID
selector and element selector. Here, you are selecting all <tr> elements which
are inside <tbody> element of GridView1 (remember that ASP.NET GridView control
is rendered as HTML table in the browser). Once selected it adds an event
handler for hover() event. You could have also used mouseover() and mouseout()
event handlers separately but hover allows you to do the same thing at one go.
The hover() event handler takes two function references. The first one is called
when mouse is over the element and the second is called when mouse comes out of
the element. In our example, when mouse is over a <tr> element you add a CSS
class to it named HoverRow and when mouse is out of the element you remove the
class. The HoverRow CSS class looks like this :
.HoverRow
{
cursor:hand;
background-color:Maroon;
color:White;
}
Notice the click() event handler of the row. To retrieve the Employee ID it
uses element selector again but with a slightly different syntax. This time it
gets only the first <td> element (Employee ID is the first column) from the
current row and then retrieves its value using text() function.
Select elements based on the combination of above options
You can also specify a combination of above selectors together, to select
matching elements. For example, consider the web form below which is similar to
the previous example, except that it allows you to read Notes about an employee
by clicking on the "Show Notes" button. The notes are displayed in a FormView
control below the GridView as shown below :
If you go by previous technique of changing alignment, it will be applicable
only for <td> elements. The notes in this case are displayed in a <p> element
with a CSS class named .Notes applied to it. If you wish to display Notes also
as per the selected alignment, you need to modify the jQuery code like this:
$(document).ready
(
function() {
$("#DropDownList1").change
(
function() {
$("td,.Notes").css("text-align",$("#DropDownList1").val());
}
)
}
)
Notice how the selector now specifies td and .Notes i.e. element selector and
CSS class selector. The .Notes class is shown below:
.Notes
{
text-align:left;
border:ridge 2px gray;
padding:6px;
}
Now that you have good understanding of basic selectors, let's move on to
basic filters.
Understanding Basic Filters
Basic filters allow you to filter elements typically returned by some
selector. For example, you may use element selector to fetch say 10 <tr>
elements but want to work with only odd or even rows at a given point of time.
This can be achieved by basic filters. Some of the common basic filters are :
- odd() - filters only odd elements from a given set
- even() - filters only even elements from a given set
- first() - returns the first element from a set
- last() - returns the last element from a set
- gt() - returns all the elements greater than a specified index from a
set
- lt() - returns all the elements lesser than a specified index from a set
- eq() - returns the element at the specified index from a set
Let's see some of these elements in action by developing an example. The
example web form is as shown below :
There is a GridView that displays records from Employees table. At the top
there is a facility to select color scheme to be applied to the GridView. You
can select a color scheme and click on the Apply button to see it in action (see
below for GridView with Black & White scheme applied).
There is also a facility to search the city column. You can search certain
records from top or bottom of the grid. The following run shows the results when
you look for London city in the last 4 rows.
Notice how the matched city entries are marked with red color. Now, let's see
the jQuery code that makes this example.
$(document).ready(function() {
$("#Button1").click(function(event) {
$("#GridView1 th").removeClass();
$("#GridView1 th").addClass($("#DropDownList1").val() + "Header");
$("#GridView1 tr:odd").removeClass();
$("#GridView1 tr:odd").addClass($("#DropDownList1").val() + "Row");
$("#GridView1 tr:even").addClass($("#DropDownList1").val() + "AlternateRow");
event.preventDefault();
})
,
$("#Button2").click(function(event) {
if ($("#DropDownList2").val() == "First") {
$("span").css("color", "black");
$("span:lt(" + $("#TextBox2").val() + "):contains
('" + $("#DropDownList3").val() + "')").css("color", "red");
}
else {
$("span").css("color", "black");
var start= $("span").length - $("#TextBox2").val() - 1;
$("span:gt(" + start + "):contains
('" + $("#DropDownList3").val() + "')").css("color", "red");
}
event.preventDefault();
})
})
The GridView formatting part goes inside the click event handler of Button1.
Notice the use of :odd and :even filters. The :odd filter filters all the odd
rows from the GridView and a CSS class is applied to the resultant set. This way
alternate rows are different with different look and feel. The CSS class names
that we create are BlueXXXX for Blue color scheme, RedXXXX for red color scheme
and so on. This way we can just append DropDownList1 value with "Row" or "AlternateRow"
and arrive at the desired CSS class name. The CSS classes are shown below:
.BlueHeader
{
background-color:Navy;
color:White;
font-weight:bold;
}
.BlueRow
{
background-color:#0066FF;
color:White;
font-weight:bold;
}
.BlueAlternateRow
{
background-color:#99CCFF;
color:White;
font-weight:bold;
}
.RedHeader
{
background-color:#800000;
color:White;
font-weight:bold;
}
.RedRow
{
background-color:#FF0000;
color:White;
font-weight:bold;
}
.RedAlternateRow
{
background-color:#FFCC99;
color:White;
font-weight:bold;
}
.BWHeader
{
background-color:#000000;
color:White;
font-weight:bold;
}
.BWRow
{
background-color:#999999;
color:White;
font-weight:bold;
}
.BWAlternateRow
{
background-color:#CCCCCC;
color:black;
font-weight:bold;
}
The searching functionality makes use of :gt() and :lt() filters and
:contains() content filter (more on content filters later). We first check if
searching is to be done in top n rows or bottom n rows. In former case we filter
all <SPAN> tags for index value less than what is specified in the TextBox3. You
might be wondering why we specified <SPAN> tag. I have made the City column as a
template column that displays the city value in Label control. Label control
gets rendered as <SPAN> element. If you don't do this then it would have
increased your computing logic slightly since there are other GridView columns
also render as <td>. Once we get <SPAN> elements less than specified index we
search through them using :contains() filter. The :contains() filter take a
string criteria and filters all elements from the set that contain the specified
criteria. The returned elements (<SPAN> tags in this case) are then applied some
CSS coloring using css() function.
$("span:lt(" + $("#TextBox2").val() + "):contains
('" + $("#DropDownList3").val() + "')").css("color", "red");
If you are searching from bottom then you first need to find the start index
to begin the searching. This is done as follows:
var start= $("span").length - $("#TextBox2").val() - 1;
The total number of <SPAN> elements minus what you specified in the TextBox2
gives you the index to be supplied to :gt() filter.
$("span:gt(" + start + "):contains
('" + $("#DropDownList3").val() + "')").css("color", "red");
That's it for now. All the examples I discussed above are available in the
download of this article. Make sure to adjust jQuery.js file path as per your
environment.
In the next part of this series I will cover some more selectors. Stay tuned!