Humming Bird Web Developer Classroom – Mastering jQuery in Easy Steps – Part II –Basics of Using jQuery for selecting elements from DOM




Welcome to the new edition of the “Humming Bird Web Developer Classroom” tutorial series.

This is the second part of the “Mastering jQuery in Easy Steps” tutorial and in this edition we are going to learn about the basic usage of jQuery with in a web page and about the first step in manipulating the DOM; i.e traversing the DOM tree and selecting a specific element using jQuery.

You can access the first part of the tutorial in the “Mastering jQuery in Easy Steps” series from HERE.

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

Consuming jQuery in a web page

In the first part of this tutorial you have learned how to include the jQuery library in to a web page. Now we are going to elaborate on that by starting to use the library to do something useful for us in a web page.

In the below given simple example we are learning to add the power of jQuery in to our page for showing a simple greeting message in the form of an alert box just after the web page is ready for manipulation.

Try out the below given code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Simple Greeting Message using jQuery on Page load</title>
<script type="text/JavaScript" src="jquery-1.3.1.min.js"></script>
</head>
<body>
<div>Hai</div>
<script>
$(document).ready(function() {
alert("Hello World from jQuery");
});
</script>
</body>
</html>

This sample page will show a simple message box when the web page is loaded. Even though this demo code in itself don’t do much high tech stuff, it is the first sneak peek in to the powers of jQuery.

$(document).ready(function() {
…..
}

A programmer can place statements with in this code block for tasks that are to be performed when the DOM is ready to be parsed and operated up on. This is in some ways similar to the window.onload event that the plain javascript programmers use but not exactly the same. While window.onload gets fired only after the complete loading of a webpage and its associated assets like images, the ready() method of jQuery provides the coder with a far more optimized way of performing tasks right when the DOM is ready for manipulation.

Why should you load your JavaScript files at the bottom part of your web page?

Most Browsers usually stop processing all the page assets when a javascript statement is found at the top portion of a web page and will wait until the script gets downloaded and compiled resulting in a visible delay in the rendering of a web page. So when you place the JavaScript at the end of the web page, it will result in much faster page loads.

JQuery also offers a shorthand version of the ready() method, which is given below:

$(function() {
        ...
      });

Before getting into the intricacies involved in using jQuery Selectors lets learn about some other basic jQuery information. In the first part of this tutorial we have seen that jQuery reduce the complexities involved in the DOM manipulations using plain JavaScript.

When a web developer utilizes jQuery for DOM operations he usually deals with 3 different scenarios. These 3 scenarios more or less covers almost all of the operations that a jQuery programmer will be handling as part of his daily routine and getting these scenarios clear in your mind will help you in taking control of this library.

  • Scenario 1: Finding the required Elements (it can be a single element or a set of multiple elements) using the jQuery selector concept and manipulating those elements using various jQuery methods.
  • Scenario 2: Utilizing the power of jQuery chaining to perform a set of DOM Manipulation tasks via multiple jQuery methods on a set of elements in a single go.
  • Scenario 3: Utilizing the jQuery wrapper set and its power of implicit iteration for performing tasks on a set of DOM elements with out using complex looping structures.

Lets take a good look at each of these scenarios with some examples.

Scenario 1: Finding specific DOM elements and performing tasks on them using jQuery selectors.

The below given example shows you how to pick a specific element with an id of ‘clock’ and set the current time to that element as its content using jQuery.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Finding specific elements in a webpage</title>
<script type="text/JavaScript" src="jquery-1.3.1.min.js"></script>
<style>
#clock{font-style:italic;}
</style>
</head>
<body>
<div>Hello Visitor. Current time is : <span id='clock'></span></div>
<script>
$(document).ready(function() {
		var cDate = new Date(); //nothing jQuery in this stmt :)
		var cTime = cDate.getHours() + " : " + cDate.getMinutes() + " : " + cDate.getSeconds()
		$('span#clock').text(cTime);
});
</script>
</body>
</html>

In the above sample code we are using a jQuery selector $(’span#clock’) for picking up a DOM element which is a span with an id attribute ‘clock’ and is using the jQuery method of text() on that element for setting its content. We will take a detailed look at the selectors in the later part of this tutorial.

Scenario 2: jQuery Chaining

This step involves using the excellent power of jQuery chaining for applying or performing multiple tasks on a set of elements, which is already selected via a jQuery selector. It allows the developer to apply series of methods or to chain a series of methods on the currently selected DOM element.

Lets illustrate 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>jQuery selectors and chaining of methods</title>
<script type="text/JavaScript" src="jquery-1.3.1.min.js"></script>
<style>
#d2{display:none;}
</style>
</head>
<body>
<div id="d1">Hai. I am DIV 1. i am unstyled :( </div>
<div id="d2">Hello. I am DIV 2</div>
<div id="d3">And I am DIV 3. me too unstyled :-( </div>
<script>
$(document).ready(function() {
	$('div#d2').text("DIV 2. The coolest Div on planet with added styles from jQuery ;) ").css({'font-size':'24px','color':'green','margin':'20px','border':'5px dashed red','padding':'20px'}).width(450).fadeIn('slow');
});
</script>
</body>
</html>

Here we are doing multiple sets of manipulations on a DIV element with an id of ‘d2′ in a chained fashion. First we are selecting the target DIV using the jQuery selector $(‘div#d2′) and are then chaining a set of multiple jQuery methods like text(), css(), width() and fadeIn() to manipulate that element in a single line of JavaScript code.

Of course you can write the above statement in to separate jQuery statements like written below.

$('div#d2').text("DIV 2. The coolest Div on planet with added styles from jQuery ;) ");
	$('div#d2').css({'font-size':'24px','color':'green','margin':'20px','border':'5px dashed red','padding':'20px'});
	$('div#d2').width(450);
	$('div#d2').fadeIn('slow');

But the problem here is that each statement requires the jQuery engine to do the DOM traversal and selection process for getting an object to the DIV with ‘d2’ id. This is a waste of processing resources and that’s why jQuery lets you reuse an already selected DOM element in a chained fashion. Chaining allow the developer to write a more optimal solution as repeated DOM traversal is not performed.

Scenario 3: jQuery Wrapper Set

This scenario deals with making use of the jQuery wrapper set for performing DOM manipulations on a set of elements (a set comprised of zero, one or more than one elements) for performing manipulations with out using complex explicit JavaScript looping structures.

When you write a jQuery selector like $(‘span’) what jQuery does is that it actually picks all the matching selector elements – in this case all SPAN elements – and returns a special construct or javascript object wrapped with the additional functionality offered by jQuery on those elements inside the construct. This set is called a jQuery wrapper and is a collection object, which is ready for the programmer to further manipulate it by applying jQuery methods. This wrapper object works with an implicit iterative behavior and relieves the programmer from the tedious task of writing additional looping structures for performing the same task on all the matching elements returned by a jQuery selector.

Lets take a look at 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>jQuery wrapper set</title>
<script type="text/JavaScript" src="jquery-1.3.1.min.js"></script>
<style>
div{display:none;font-size:24px;color:white;margin:20px;border:5px dashed #ccc;padding:20px;width:200px;background-color:#000;float:left;}
</style>
</head>
<body>
<div id="d1">We are all Divs! cloned like Agent Smith</div>
<div id="d2">We are all Divs! cloned like Agent Smith</div>
<div id="d3">We are all Divs! cloned like Agent Smith</div>
<script>
$(document).ready(function() {
	$('div').fadeIn('slow');
});
</script>
</body>
</html>

The above example finds all the DIV elements on the current page using the $(‘div’) selector and we are using the fadeIn() method on the wrapper set returned by jQuery. Since jQuery handles the selectors with a wrapper object, it will have all the 3 DIVS found on the page within the wrapper and the jQuery implicit iterative behavior applies the fadeIn() method to all the 3 elements.

Since we have seen almost all the normal scenarios associated with finding and manipulating DOM elements we will be elaborating on them with code specific knowledge in the forthcoming part of this tutorial.

What is jQuery() function? Is it the same as $()?

It is the same as the $() function that you use as part of the jQuery selector statement. $() is an alias for the jQuery() function which returns a wrapper set of objects matching the selector criteria written.

So in the above example the

$('span#clock').text(cTime);

statement can be written as

jQuery('span#clock').text(cTime);

More about jQuery Selectors

Accessing and manipulating individual page elements are made super easy by the excellent element selector facility provided by the jQuery library. JQuery adapts the concept of selectors from the CSS language and it allows a developer to easily and quickly access a specific or an array of elements from the DOM tree.

The basic syntax of a jQuery selector is:

$('selector_string') 

Here the ’selector_string’ can be any valid CSS based selector string or a javacript based object pointing to an actual DOM element.

With a jQuery selector you can pick individual or groups of elements from the DOM using the elements ID, class, tag names, attributes or specific events; all you have to do is to write the appropriate selector strings.

Multiple selectors can be sent in to the $() function using the below given format

$('selector_string1,selector_string2')

Lets take a look at some common criteria’s associated with the usage of jQuery selectors with in a web page:

1. Finding a specific element on a page using jQuery selector based on the elements ID

In order to pick an element from the DOM tree based on the ID associated with it, all you have to do is to use the jQuery selector logic in the following syntax:

$('element#id') or ('#id')

We are just passing a selector string based on the id of an element in to the $() function of the jQuery to create a wrapper set which we can use.

Lets take a look at 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>jQuery selector - selecting using ID</title>
<script type="text/JavaScript" src="jquery-1.3.1.min.js"></script>
<style>
div{font-size:24px;color:white;margin:20px;border:5px dashed #ccc;padding:20px;width:200px;background-color:#000;float:left;}
</style>
</head>
<body>
<div id="d1">We are all Divs! cloned like Agent Smith. I am Div 1</div>
<div id="d2">We are all Divs! cloned like Agent Smith. I am Div 2 and i am the selected DIV</div>
<div id="d3">We are all Divs! cloned like Agent Smith. I am Div 3</div>
<script>
$(document).ready(function() {
	$('#d2').css({'border':'5px dashed red'});
});
</script>
</body>
</html>

In this sample code we are picking a specific DIV with an id ‘d2′ with the selector $(‘#d2′) and are applying a different visual style on that element using the css() method of jQuery.

In the above given sample you can select the two DIVs with ‘d1′ and ‘d2′ as Id’s in a jQuery Selector using the following code.

$('#d1,#d2'). css({'border':'5px dashed red'});

2. Finding Specific Elements falling with in a specific context and manipulating them.

Here we are looking at ways in which you can select an element coming under a specific context, like a bold tag coming under a specific DIV or a span element coming inside a specific DIV etc.

Here is 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>jQuery selector - selecting elements from a context</title>
<script type="text/JavaScript" src="jquery-1.3.1.min.js"></script>
<style>
div{font-size:24px;color:white;margin:20px;border:5px dashed #ccc;padding:20px;width:200px;background-color:#000;float:left;}
</style>
</head>
<body>
<div id="d1">We are all Divs! cloned like Agent Smith. <span>I am Div 1</span></div>
<div id="d2">We are all Divs! cloned like Agent Smith.  <span>I am Div 2</span></div>
<div id="d3">We are all Divs! cloned like Agent Smith.  <span>I am Div 3</span></div>
<script>
$(document).ready(function() {
	$('span').css({'color':'green'});
	$('div#d2 span').css({'border':'5px dashed red'});
});
</script>
</body>
</html>

Here we are finding all the SPAN elements coming under the page using the $(’span’) selector. Further we are selecting a specific SPAN element coming under a DIV tag with an id of ‘d2′ using the $(‘div#d2 span’) selector.

Finding elements with specific class styles.

You can also select a specific or a set of elements on a page using specific style classes applied to the elements.

This can be demonstrated as:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>jQuery selector - selecting elements using style classes</title>
<script type="text/JavaScript" src="jquery-1.3.1.min.js"></script>
<style>
.p1 {
color:green;
}
.p2 {
color:red;
}
.p3 {
color:blue;
}
.innerDiv{width:530px;border:1px solid #ccc;}
.insideP {
color:black;
width:500px;
padding:15px;
font-size:16px;
line-height:18px;
font-style:italic;
}
.insideP span{font-weight:bold;}
</style>
</head>
<body>
<p class="p1">
This is Paragraph 1.<br />
Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.
</p>
<p class="p2">
This is Paragraph 2. <br />

"If the world were merely seductive, that would be easy. If it were merely challenging, that would be no problem. But I arise in the morning torn between a desire to improve the world and a desire to enjoy the world. This makes it hard to plan the day."
— E.B. White
</p>
<p class="p3">
This is Paragraph 3. <br/>
"There is a theory which states that if ever anyone discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable.
There is another theory which states that this has already happened."
— Douglas Adams
</p>
<div class="innerDiv">
<p>"Beauty is in the eye of the beholder and it may be necessary from time to time to give a stupid or misinformed beholder a black eye."
— <span>Jim Henson</span></p>
<p>
"The trouble with having an open mind, of course, is that people will insist on coming along and trying to put things in it."
— <span>Terry Pratchett </span>
</p>
</div>
<script>
$(document).ready(function() {
	$('p.p2').slideUp(2000);
	$('div.innerDiv p').addClass('insideP');
});
</script>
</body>
</html>

Here we are selecting a paragraph with a style class of p2 using the $(‘p.p2′) selector and are applying a jQuery slideUp animation to hide that paragraph. To further elaborate the concept we are selecting all the paragraphs inside a div with a class of ‘innerDiv’ – using the $(‘div.innerDiv p’) selector – and are applying the jQuery addClass() method to attach a new class to each of the paragraphs wrapped inside the jQuery wrapper set.

Conclusion

Here in this edition of the jQuery classroom we have learned about using the jQuery library in a web page and about the concepts of jQuery selectors, jQuery wrapper set and jQuery chaining. We have also had hands on experience on doing basic selection operations using the jQuery selector construct. In the next edition of the “Mastering jQuery in Easy Steps” tutorial we will be learning all about the various advanced options and operations that we can do with the jQuery selectors.

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 – III – Selecting DOM Elements With Advanced jQuery Selectors – Session 1
  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 (2)

ADD A COMMENT

Name (required)

Email (required)

Website

Reload Image

Comments