Humming Bird Web Developer Classroom – Mastering jQuery in Easy Steps – III – Selecting DOM Elements With Advanced jQuery Selectors – Session 1

Welcome to the new edition of the “Humming Bird Web Developer Classroom” tutorial series. This is the first session of the third part of the “Mastering jQuery in Easy Steps” tutorial and in the previous two editions we have covered a lot of ground regarding the basic usage of this fantastic JavaScript library. We have learned things like including and consuming jQuery library with in a web page, the possible things that can be done using this library and some of the basic methods of selecting individual or a set of specific DOM elements using this library.

In this edition of this jQuery tutorial we will be learning about the advanced methods offered by jQuery with which you can find and select a specific set of elements for manipulation with in your code. Before you have to perform any action on a DOM element, the first step involved is to get a reference to the desired element; and this is exactly what a jQuery selector is provided for.

You can access the first two parts of the tutorial in the “Mastering jQuery in Easy Steps” series from Part 1 and Part 2.

You can download all the sample files associated with this third edition of the tutorial in “Mastering jQuery in Easy Steps” series from HERE

Since this chapter covers a lot of ground we have split it in to two sessions for your reading convenience. The second session can be accessed from Session 2 of Part 3

In the first two chapters while learning about the basics of the jQuery usage we have seen that jQuery utilizes the simple but powerful selector syntax used by the CSS specifications for selecting elements with in the DOM. We have also looked at writing some simple jQuery selector statements too. We have seen that the basic jQuery selector syntax is

$('selector_string') 

which will provide you with a jQuery wrapper set containing the elements that where picked by the jQuery engine from the DOM matching the ’selector_string’ selector criteria.

In this chapter we are going to add on to that knowledge to create a wide variety of jQuery selectors based on various element factors like simple tag names, id and class names, attributes, states of elements, their order and hierarchy in the DOM tree etc.

Let’s take a look at these selectors one by one:

1. ID Selector – Selecting an Element by it’s ID

In order to select an element from the DOM tree using an elements id, all you have to do is to pass the id preceded by a # symbol to the jQuery function as given below.

$('#myid')

The above code will select the unique element inside the DOM tree with ‘myid’ set as its id. A point to note while using the ID selector is that the id is expected to be unique inside a page and jQuery will return only the first element found on the page with the id provided even if multiple elements are sharing the same id. You can be specific while providing the jQuery function with selector strings like ‘div#myid’ to make sure that only a DIV element with the ‘myid’ set as its id attribute is selected.

This is similar to document.getElementById and the library internally uses the same JavaScript function to make the ID based selection.

2. Element Selector – Selecting all the elements with specific HTML Tags

This is the selector you want to use if you need to pick elements from the DOM based on the HTML tag name. You can pass any valid HTML tag name in to this selector.

$('p')

This above element selector will result in a jQuery wrapper set made up of all the paragraph tags found on a target page.

This selector is similar to the plain document.getElementsByTagName and the jQuery library internally utilizes this function to make the selections.

3. Class Selector – Selecting all the elements with specific css class associated with them.

This selector helps the developer to make a jQuery wrapper set containing all elements with in the DOM, which are associated with a specific class name.

$('.firstlevel') 

The above piece of jQuery selector code will make a wrapper set containing all the elements with in the current page, which have a class of ‘firstlevel’. You can refine the selector to be more specific by writing it like:

$('span .firstlevel') 

which will create a wrapper set made up of only those elements which are children of a span element and which have a classname set of ‘firstlevel’.

If you are critically concerned about performance optimization then the class selector can cause you some issues. Because of the lack of a native JavaScript function, which performs this same operation, jQuery makes class based selections by scanning all the elements inside the DOM for class based matches. This may cause some extra resource usage in large and complex web pages.

4. The Universal Selector * – Choosing all elements with in a context

This selector can be used to pick all the elements, which comes under a specific DOM element.

$('*')

The above selector statement will pick all the elements coming under the DOM. This can be further rewritten to be more specific in scenarios like:

$('body *')

or

$('#nav *')

In the first case the wrapper set is made using all the elements coming under the body elements with in the DOM and in the second case the wrapper set is comprised of all the elements coming under an element with an ID of ‘#nav’.

5. Selecting Elements using Multiple Selector marker

The comma combinator (,) can be used to select elements matching multiple selector expressions.

$(#wrapper h1, h2, p)

The above given selector has 3 different selector expressions separated with commas and will result in a selector set made up of all H1, H2 and paragraph elements with in an element with wrapper id.

6. Making Selection based on the hierarchy of elements with in the DOM

You can write precise selector strings, which point to specific sets of elements in a page by providing the ancestry, child or parent combinator of the elements with in the selector string. This can be used to pick elements, which come as direct descendants of a specific element in the DOM, or to pick elements, which occur after another specific element with in the DOM etc.

Understanding Ancestors, Parents, Descendants, Children and Siblings in a DOM context

It is important that as a developer you should be able to identify the hierarchical position of an element in the DOM tree. The DOM tree resembles a family hierarchy tree and you should be able to understand the various lingo associated with this tree by looking at the below given sample page code and its DOM structural graphic.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Direct Descendents Selector example</title>
</head>
<body>
<h1>I am a Header</h1>
<div id="first">
<p>Nominally a great age of scientific inquiry, ours has actually become an
age of superstition about the infallibility of science; of almost mystical
faith in its nonmystical methods; above all . . . of external verities; of
traffic-cop morality and rabbit-test truth.<strong>Kronenberger, L</strong></p>
<p>Think of all the men who never knew the answers<br/>
think of all those who never even cared.<br/>
Still there are some who ask why<br/>
who want to know, who dare to try.<strong>McKuen, Rod</strong></sp>
</div>

<h1>I am another Header</h1>
<div id="second">
<p>Nominally a great age of scientific inquiry, ours has actually become an
age of superstition about the infallibility of science; of almost mystical
faith in its nonmystical methods; above all . . . of external verities; of
traffic-cop morality and rabbit-test truth.<strong>Kronenberger, L</strong></p>
<p>Think of all the men who never knew the answers<br/>
think of all those who never even cared.<br/>
Still there are some who ask why<br/>
who want to know, who dare to try.<strong>McKuen, Rod</strong></sp>
</div>
</body>
</html>

The above code can be represented in a family tree like structure as:

Here HTML is the root element, and so it can be called as the ancestor of all the other elements in that sample page. It also means that all other elements can be called as the descendants of the HTML element. If you look closely you will find that the HTML element has 2 direct descendents in HEAD and BODY elements; so they are the children of the HTML element. So the HTML element in turn is not just an ancestor to those two tags but it is their parent too. HEAD and BODY are at the same level and they are sibling elements.

The differentiation between a descendant and children is actually very simple. All elements residing with in another element are its descendants while only those descendants which are directly enclosed with in an element are only considered as its children.

If you look further in to the above code and its tree representation you can identify other members of the family tree as 2 H1 elements and 2 DIV elements as children of the BODY element which means that the BODY tag is a parent to those 4 elements and those 4 elements are siblings of each other. The 2 paragraphs residing inside each of the DIV elements make them siblings to each other, the children of the DIV elements and descendants of the BODY tag. In this way you can identify the hierarchical position and order of each element inside the DOM structure of any valid HTML page. Knowing these orders and positions will enable you to write much-refined selector strings for jQuery.

Selecting Direct Descendants of an Element – Making the wrapper set on the first level descendants or children of a DOM element.

We have seen that we can specifically select elements, which are descendants of another DOM element using the following selector syntax.

$('element1_selector_string element2_selector_string ')

This will make sure that all the elements, which match the ‘element2_selector_string’ and contained inside an element with the ‘element1_selector_string’, will be wrapped into a jQuery wrapper set. But if we have to limit the selection only to the direct descendants of an element then we can use the following syntax.

$('element1_selector_string > element2_selector_string ')

Lets elaborate this with an example.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Direct Descendents Selector example</title>
<script type="text/JavaScript" src="jquery-1.3.1.min.js"></script>
<style>
h1{font-family:verdana;font-size:14px;}
#first{
margin:25px;
border:5px solid #ccc;
width:900px;
height:250px;
font-family:Tahoma;
font-size:13px;
}
strong {padding-left:15px;}
#second{
margin:25px;
border:5px solid #ccc;
width:900px;
height:250px;
font-family:Tahoma;
font-size:13px;
}
div {padding:15px;}
</style>
</head>
<body>
<h1>Not using the Direct Descendents Selector</h1>
<div id="first">
<span>Nominally a great age of scientific inquiry, ours has actually become an
age of superstition about the infallibility of science; of almost mystical
faith in its nonmystical methods; above all . . . of external verities; of
traffic-cop morality and rabbit-test truth.<strong>Kronenberger, L</strong></span><br/><br/>
<span>Think of all the men who never knew the answers<br/>
think of all those who never even cared.<br/>
Still there are some who ask why<br/>
who want to know, who dare to try.<strong>McKuen, Rod</strong></span><br/><br/>
<span>Science proceeds by successive answers to questions more and more
subtle, coming nearer and nearer to the very essence of phenomena.<strong>Pasteur, Louis</strong></span>
<p>All the above given Quotes deal with <span>Science</span></p>
</div>

<h1>Using the Direct Descendents Selector</h1>
<div id="second">
<span>Nominally a great age of scientific inquiry, ours has actually become an
age of superstition about the infallibility of science; of almost mystical
faith in its nonmystical methods; above all . . . of external verities; of
traffic-cop morality and rabbit-test truth.<strong>Kronenberger, L</strong></span><br/><br/>
<span>Think of all the men who never knew the answers<br/>
think of all those who never even cared.<br/>
Still there are some who ask why<br/>
who want to know, who dare to try.<strong>McKuen, Rod</strong></span><br/><br/>
<span>Science proceeds by successive answers to questions more and more
subtle, coming nearer and nearer to the very essence of phenomena.<strong>Pasteur, Louis</strong></span>
<p>All the above given Quotes deal with <span>Science</span></p>
</div>
<script>
$(document).ready(function() {
$('#first span').css({'font-style':'italic','color':'green','font-size':'14px'});
$('#second > span').css({'font-style':'italic','color':'green','font-size':'14px'});
});
</script>
</body>
</html>

Closely watch the two boxes formed by the two DIVS inside the demo page of the above sample code. In each DIV we are placing some content inside 3 SPAN elements followed by a paragraph with another SPAN element wrapped inside the paragraph tag.

In the jQuery code we are writing the first selector as below

$('#first span').css({'font-style':'italic','color':'green','font-size':'14px'});

We are picking all the span elements coming inside an element marked with an ID of ‘first’ and are applying some visual styling dynamically. JQuery picks all the four SPAN elements inside the DIV with the ID of ‘first’ including the one which is a child of a paragraph tag. You can see in the DEMO page that the SPAN inside the paragraph is applied with the visual formatting.

In the second line of jQuery we are using a direct descendent marker in the form of a ‘>’ inside the selector string.

$('#second > span').css({'font-style':'italic','color':'green','font-size':'14px'});

Here the $(‘#second > span’) selector string ensures that only those SPAN elements which are the direct or first level child elements of the element with ’second’ as ID is returned in the wrapper set. This results in only the first 3 SPAN tags inside the second DIV being selected. Since the last SPAN is inside a paragraph it is not a direct descendant of the second DIV and it is left out of the wrapper set.

Selecting Siblings with the Adjacent Siblings marker (+) and General Siblings marker (~)

These two selectors allow you to pick specific siblings of an element in the DOM.

Adjacent Siblings marker

The adjacent siblings marker allows you to select the sibling of a DOM element which immediately follow it or which is an immediate neighbor of it.

Lets elaborate this with an example.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Adjacent Siblings Selector example</title>
<script type="text/JavaScript" src="jquery-1.3.1.min.js"></script>
<style>
h1{font-family:verdana;font-size:15px;}
#wrapper{
margin:25px;
border:5px solid #ccc;
width:900px;
font-family:Tahoma;
font-size:13px;
}
p{margin:0;padding:5px;padding-bottom:3px;border-bottom:1px solid #fff;}
strong {padding-left:15px;}
div {padding:5px;}
</style>
</head>
<body>
<h1>Adjacent Siblings</h1>
<div id="wrapper">
<h1>Deepest Lakes</h1>
<div>
<p>Baikal, Russia - depth 1,637 metres</p>
<p>Tanganyika, Burundi/Tanzania/Dem. Rep. of Congo/Zambia - depth 1,470 metres</p>
<p>Caspian Sea, Azerbaijan/Iran/Kazakhstan/Russia/Turkmenistan - depth 1,025 metres</p>
<p>Malawi, Malawi/Mozambique/Tanzania- depth 706 metres</p>
<p>Issyk Kul, Kyrgyzstan - depth 702 metres</p>
</div>
<h1>Longest Rivers</h1>
<div>
<p>Nile (Bahr-el-Nil) - length 6,725 km</p>
<p>Amazon (Amazonas)  - length 6,448 km</p>
<p>Yangtze-Kiang (Chang Jiang)  - length 6,380 km</p>
<p>Mississippi-Missouri - length 5,970 km</p>
<p>Yenisey-Angara - length 5,536 km</p>
</div>
<h1>Highest Mountains</h1>
<div>
<p>Mt Everest (Qomolangma) - height 8,850 metres</p>
<p>K2 (Qogir) - height 8,611 metres</p>
<p>Kangchenjunga - height 8,597 metres</p>
<p>Lhotse I - height 8,510 metres</p>
<p>Makalu I - height 8,480 metres</p>
</div>
</div>

<script>
$(document).ready(function() {
$('#wrapper h1+div').css({'font-style':'italic','background-color':'#7384DD','font-size':'14px'});

$('#wrapper h1').click(function() {
								  $(this).find('+div').css({'background-color':'#3650CE'});
								  });

});
</script>
</body>
</html>

Here each of the H1 tag inside the ‘#wrapper’ DIV has an adjacent sibling which is a DIV element. By using the

$('#wrapper h1+div')

selector, we are picking each of these adjacent Divs and are manipulating its background color. We have also added a click event to each of these H1 tags and are choosing their adjacent sibling DIV using the

$(this).find('+div')

marker.

General Siblings marker

The general siblings marker allows you to select all the siblings of a DOM element, which follows it. This marker helps in picking all the siblings coming after an element without checking for their adjacency.

Lets elaborate this with an example.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>General Siblings Selector example</title>
<script type="text/JavaScript" src="jquery-1.3.1.min.js"></script>
<style>
h1{font-family:verdana;font-size:15px;}
#wrapper{
margin:25px;
border:5px solid #ccc;
width:900px;
font-family:Tahoma;
font-size:13px;
}
p{margin:0;padding:4px;padding-bottom:3px;border-bottom:1px solid #fff;}
strong {padding-left:15px;}
div {padding:5px;}
</style>
</head>
<body>
<h1>General Siblings</h1>
<p>Click on each of the headings to select its Adjacent Sibing.
<div id="wrapper">
<div>
<h1>Deepest Lakes</h1>
<p>Baikal, Russia - depth 1,637 metres</p>
<p>Tanganyika, Burundi/Tanzania/Dem. Rep. of Congo/Zambia - depth 1,470 metres</p>
<p>Caspian Sea, Azerbaijan/Iran/Kazakhstan/Russia/Turkmenistan - depth 1,025 metres</p>
<p>Malawi, Malawi/Mozambique/Tanzania- depth 706 metres</p>
<p>Issyk Kul, Kyrgyzstan - depth 702 metres</p>
</div>
<div>
<h1>Longest Rivers</h1>
<p>Nile (Bahr-el-Nil) - length 6,725 km</p>
<p>Amazon (Amazonas)  - length 6,448 km</p>
<p>Yangtze-Kiang (Chang Jiang)  - length 6,380 km</p>
<p>Mississippi-Missouri - length 5,970 km</p>
<p>Yenisey-Angara - length 5,536 km</p>
</div>
<div>
<h1>Highest Mountains</h1>
<p>Mt Everest (Qomolangma) - height 8,850 metres</p>
<p>K2 (Qogir) - height 8,611 metres</p>
<p>Kangchenjunga - height 8,597 metres</p>
<p>Lhotse I - height 8,510 metres</p>
<p>Makalu I - height 8,480 metres</p>
</div>
</div>

<p><em>* Geo Data taken from Whitaker's Almanac 2010.</em></p>

<script>
$(document).ready(function() {
$('#wrapper h1~p').css({'font-style':'italic','background-color':'#7384DD','font-size':'14px'});

$('#wrapper h1').click(function() {
								  $(this).find('~p').css({'color':'#3650CE'});
								  });

});
</script>
</body>
</html>

In this example each of the H1 and the paragraphs are enclosed with in separate DIV tags. We are choosing all the paragraphs coming after each of the H1 tags using the generic siblings marker with the following code.

$('#wrapper h1~p')

We are also using a click event attached to each of these H1 tags for choosing all the sibling paragraphs associated with the H1 tag for manipulating their style using the

$(this).find('~p')

marker.

Conclusion

Since there are many more powerful jQuery selectors left to experience we are taking a break with the present session and are continuing the rest of the part 3 of this classroom as a separate post.

Rate this post:
Loading ... Loading ...
HB Admin's Gravatar icon

Author: HB Admin

Admin of Humming Bird Designs Blog

98 articles posted by HB Admin.

Related Posts

  1. Humming Bird Web Developer Classroom – Mastering jQuery in Easy Steps – Part II –Basics of Using jQuery for selecting elements from DOM
  2. jQuery Web Page Content Indexer Plugin
  3. From The Mad Lab – A CSS3 & jQuery based Japanese Paper Fan Image Gallery
  4. Workshop for Absolute Beginners – How to build an easy to manage vertical menu for your website using CSS, PHP and jQuery
  5. Wikipedia Content Indexer Menu Greasemonkey Plugin
SUBSCRIBE
Enjoyed this post? Subscribe to HB BLOG.

COMMENTS (1)

ADD A COMMENT

Name (required)

Email (required)

Website

Reload Image

Comments