As I promised in this part i am going to cover in depth of how to select/find elements from the DOM. One important thing I want to point out is about jQuery objects. We will use various methods for getting the DOM element. Once we get it, it will be in the form of jQuery object and this object is entirely different from the HTML element. And hence the properties and method will be different.
Selectors start with $() function which basically removes the need for a loop to access the group of elements as the objects are automatically looped and added by jQuery. Some examples
$(‘div’) – get all div elements in the document
$(‘#elementid’) – get all elements in the document having the given id
$(‘.classname’) – get all elements in the document having the class assigned to the given classname
Lets start Part 2 example by creating a website as we discussed in Part 1. Replace the code in default.aspx with the one provided below
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Part2._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script src="jquery-1.3.2.js" type="text/javascript"></script>
<style type="text/css">
.horizontal
{
float: left;
list-style: none;
margin: 10px;
}
</style>
</head>
<script type="text/javascript" language="javascript">
</script>
<body>
<form id="form1" runat="server">
<ul id="os">
<li>Windows
<ul>
<li>DOS</li>
<li>Win 95</li>
<li>Win 98</li>
<li>Win ME</li>
<li>Win XP</li>
<li>Win Vista</li>
<li>Win 7</li>
</ul>
</li>
<li>Unix
<ul>
<li>Unix</li>
<li>Solaris</li>
<li>Linux</li>
</ul>
</li>
</ul>
</form>
</body>
</html>
The output of the website will be as follows
Now lets apply the Style “horizontal”. Add the below code in your page file.
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#os > li').addClass('horizontal');
});
</script>
Here we are using the child combinator ( > ) to get all list items that is a child of an element with an ID of os (#os). The output of this query will make the page as follows
We can use the negation pseudo-class to identify all list items that do not have a class of horizontal. For that we will be using the following code.
$('#os li:not(.horizontal)').addClass('sub-level');
and the sub-level class will be
.sub-level
{
background-color: Yellow;
}
The jQuery will get all list items that do not have class horizontal, and for those list items it will apply the style sub-level. The output will be as shown below.
jQuery supports a set of basic XPath selectors. For selecting attributes jQuery uses XPath selectors. For example, for selecting all div which as width attributes
$('div[@width]')
Another scenario is if we want to get the element which contains another element
$('div[table]')
The above statements will get all the div’s which has a table.
Using XPath we can find if the attribute starts with a string as follows
$('a[@href^="mailto:"')
The above statement will get all anchor tag with attribute href starts with mailto
Similarly for finding the ending with
$('a[@href$=".aspx"')
This will find all anchor tags with href attribute ending with aspx extension
$('a[@href*="domain"')
Above query will find all anchor tags with href attribute containing the string domain anywhere.
All the selectors discussed return a set of elements, from the set if we want to access elements by index, we can use the Custom selector. Similar to array index, the index starts with 0.
$('div.horizontal:eq(0)')
Since CSS index is one based, in CSS selector we must use 1 to get the 1st element.
Two important custom selector included in jQuery are odd and even. For demonstrating this, let’s add a table element to our as shown below.
<table>
<tr>
<td>
SomeData1
</td>
<td>
SomeData2
</td>
</tr>
<tr>
<td>
SomeData3
</td>
<td>
SomeData4
</td>
</tr>
<tr>
<td>
SomeData5
</td>
<td>
SomeData6
</td>
</tr>
<tr>
<td>
SomeData7
</td>
<td>
SomeData8
</td>
</tr>
<tr>
<td>
SomeData9
</td>
<td>
SomeData10
</td>
</tr>
</table>
Include the below style for creating alternate rows
<style type="text/css">
.odd-style
{
background-color: Olive;
}
.even-style
{
background-color: Aqua;
}
</style>
Now let’s see how jQuery can apply those styles to the table.
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('tr:odd').addClass('odd-style');
$('tr:even').addClass('even-style');
});
</script>
Here is the output
The first row index is 0 so its treated as even.
$('td:contains("somedata4")').addClass('bold');
will produce the following output
Let’s explore some DOM Traversal methods
$('tr').filter(':odd').addClass('odd-style');
This is another way to traverse the DOM and the impact is same as the statement we used for applying odd-style in previous scenario. I am going to add headers to our table by placing the following to the beginning of the table element.
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
Now the jQuery is modified as follows
$('th').parent().addClass('heading-style');
$('tr:not([th]):even').addClass('even-style');
$('tr:not([th]):odd').addClass('odd-style');
$('td:contains("SomeData3")').addClass('bold');
1st statement will get the parent of ‘th’ which will be the 1st tr and apply the style heading-style
2nd statement will get all tr even which don’t have a th element and applies the even-style
3rd statement will get all tr odd which don’t have a th element and applies the odd-style
4th statement remains the same as previous but only change is here i am making the 3rd cell bold. This is done to explain the next statement :-)
$('td:contains("SomeData3")').next().addClass('bold');
This will apply the style bold to the next cell following cell which has data “SomeData3”.
Some more samples.
$('td:contains("SomeData3")').siblings().addClass('bold');
$('td:contains("SomeData3")').parent().find('td:gt(0)')
.addClass('highlight');
$('td:contains("SomeData3")').parent().find('td').not(':contains("SomeData3")')).addClass('bold');
$('td:contains("SomeData3")').parent().find('td:eq(1)').addClass(
'bold').end().find('td:eq(2)').addClass('bold');
Hope you reached a level to understand the above statements. Else add it to your website and do some experiments :-)
Add one more column to our table and use the following jQuery
$('td:contains("SomeData3")') //get every cell containing "SomeData3"
.parent() //get its parent
.find('td:eq(1)') //find inside the parent the 2nd cell
.addClass('bold') //add the "bold" class to that cell
.end() //revert back to the parent of the cell containing "SomeData3"
.find('td:eq(2)') //find inside the parent the 3rd cell
.addClass('bold'); //add the "bold" class to that cell
If you want to find the tag name of an element with id “myId”, use the following statement
var myTag = $('#myId').get(0).tagName;
var myTag = $('#myId')[0].tagName;
Both will do the same job. This is the end of part 2. Hope it was a good learning. In part 3 I am planning to explain about Event and jQuery.