JQuery-Handling an Element

Posted: March 17, 2011 in Uncategorized

Find some elements and do something with them
Or more specifically stated, locate a set of elements in the DOM, and then do something
with that set of elements. For example, let’s examine a scenario where you want to hide
a <div> from the user, load some new text content into the hidden <div>, change an
attribute of the selected <div>, and then finally make the hidden <div> visible again.
This last sentence translated into jQuery code would look something like this:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html>
<head>
<script type=”text/JavaScript”
src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script&gt;
</head>
<body>
<div>old content</div>
<script>
//hide all divs on the page
jQuery(‘div’).hide();
//update the text contained inside of all divs
jQuery(‘div’).text(‘new content’);
//add a class attribute with a value of updatedContent to all divs
jQuery(‘div’).addClass(“updatedContent”);
//show all divs on the page
jQuery(‘div’).show();
</script>
</body>
</html>
Let’s step through these four jQuery statements:
• Hide the <div> element on the page so it’s hidden from the user’s view.
• Replace the text inside the hidden <div> with some new text (new content).
• Update the <div> element with a new attribute (class) and value (updatedContent).
• Show the <div> element on the page so it’s visible again to the viewing user.
If the jQuery code at this point is mystical syntax to you, that’s OK. We’ll dive into the
basics with the first recipe in this chapter. Again, what you need to take away from this
code example is the jQuery concept of “find some elements and do something with them.” In our code example, we found all the <div> elements in the HTML page using
the jQuery function (jQuery()), and then using jQuery methods we did something with
them (e.g., hide(), text(), addClass(), show()).

Chaining
jQuery is constructed in a manner that will allow jQuery methods to be chained. For
example, why not find an element once and then chain operations onto that element?
Our former code example demonstrating the “Find some elements and do something
with them” concept could be rewritten to a single JavaScript statement using chaining.
This code, using chaining, can be changed from this:
//hide all divs on the page
jQuery(‘div’).hide();
//update the text contained inside of the div
jQuery(‘div’).text(‘new content’);
//add a class attribute with a value of updatedContent to all divs
jQuery(‘div’).addClass(“updatedContent”);
//show all divs on the page
jQuery(‘div’).show();
to this:
jQuery(‘div’).hide().text(‘new content’).addClass(“updatedContent”).show();
or, with indenting and line breaks, to this:
jQuery(‘div’)
.hide()
.text(‘new content’)
.addClass(“updatedContent”)
.show();
Plainly speaking, chaining simply allows you to apply an endless chain of jQuery methods
on the elements that are currently selected (currently wrapped with jQuery functionality)
using the jQuery function. Behind the scenes, the elements previously selected
before a jQuery method was applied are always returned so that the chain can continue.
As you will see in future recipes, plugins are also constructed in this manner (returning
wrapped elements) so that using a plugin does not break the chain.
If it’s not immediately obvious, and based on the code in question, chaining also cuts
down on processing overhead by selecting a set of DOM elements only once, to then
be operated on numerous times by jQuery methods by way of chaining. Avoiding unnecessary
DOM traversing is a critical part of page performance enhancements. Whenever
possible, reuse or cache a set of selected DOM elements.

The jQuery wrapper set
A good majority of the time, if jQuery is involved, you’re going to be getting what is
known as a wrapper. In other words, you’ll be selecting DOM elements from an HTML
page that will be wrapped with jQuery functionality. Personally, I often refer to this as
a “wrapper set” or “wrapped set” because it’s a set of elements wrapped with jQuery
functionality. Sometimes this wrapper set will contain one DOM element; other times
it will contain several. There are even cases where the wrapper set will contain no
elements. In these situations, the methods/properties that jQuery provides will fail
silently if methods are called on an empty wrapper set, which can be handy in avoiding
unneeded if statements.
Now, based on the code we used to demonstrate the “Find some elements and do
something with them” concept, what do you think would happen if we added multiple
<div> elements to the web page? In the following updated code example, I have added
three additional <div> elements to the HTML page, for a total of four <div> elements:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html>
<head>
<script type=”text/JavaScript” src=”http://ajax.googleapis.com/ajax/libs/
jquery/1.3.0/jquery.min.js”></script> </head>
<body>
<div>old content</div>
<div>old content</div>
<div>old content</div>
<div>old content</div>
<script>
//hide all divs on the page
jQuery(‘div’).hide().text(‘new content’).addClass(“updatedContent”).show();
</script>
</body>
</html>

You may not have explicitly written any programmatic loops here, but guess what?
jQuery is going to scan the page and place all <div> elements in the wrapper set so that
the jQuery methods I am using here are performed (aka implicit iteration) on each
DOM element in the set. For example, the .hide() method actually applies to each
element in the set. So if you look at our code again, you will see that each method that
we use will be applied to each <div> element on the page. It’s as if you had written a
loop here to invoke each jQuery method on each DOM element. The updated code
example will result in each <div> in the page being hidden, filled with updated text,
given a new class value, and then made visible again.
Wrapping your head around (pun intended) the wrapper set and its default looping
system (aka implicit iteration) is critical for building advanced concepts around looping.
Just keep in mind that a simple loop is occurring here before you actually do any
additional looping (e.g., jQuery(‘div’).each(function(){}). Or another way to look at this is each element in the wrapper will typically be changed by the jQuery method(s)
that are called.
Something to keep in mind here is there are scenarios that you will learn about in the
coming chapters where only the first element, and not all the elements in the wrapper
set, is affected by the jQuery method (e.g., attr()).

How the jQuery API Is Organized
There is no question that when I first started out with jQuery, my main reason for
selecting it as my JavaScript library was simply that it had been properly documented
(and the gazillion plugins!). Later, I realized another factor that cemented my love affair
with jQuery was the fact that the API was organized into logical categories. Just by
looking at how the API was organized, I could narrow down the functionality I needed.
Before you really get started with jQuery, I suggest visiting the documentation online
and simply digesting how the API is organized. By understanding how the API is organized,
you’ll more quickly navigate the documentation to the exact information you
need, which is actually a significant advantage given that there are really a lot of different
ways to code a jQuery solution. It’s so robust that it’s easy to get hung up on implementation
because of the number of solutions for a single problem. I’ve replicated here
for you how the API is organized. I suggest memorizing the API outline, or at the very
least the top-level categories.
• jQuery Core
— The jQuery Function
— jQuery Object Accessors
— Data
— Plugins
— Interoperability
• Selectors
— Basics
— Hierarchy
— Basic Filters
— Content Filters
— Visibility Filters
— Attribute Filters
— Child Filters
— Forms
— Form Filters
• Attributes
— Attr
— Class
— HTML
— Text
— Value
• Traversing
— Filtering
— Finding
— Chaining
• Manipulation
— Changing Contents
— Inserting Inside
— Inserting Outside
— Inserting Around
— Replacing
— Removing
— Copying
• CSS
— CSS
— Positioning
— Height and Widths
• Events
— Page Load
— Event Handling
— Live Events
— Interaction Helpers
— Event Helpers
• Effects
— Basics
— Sliding
— Fading
— Custom
— Settings
• Ajax
— AJAX Requests
— AJAX Events
— Misc.
• Utilities
— Browser and Feature Detection
— Array and Object Operations
— Test Operations
— String Operations
— Urls

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s