jQuery in Action
34
CHAPTER 2
Creating the wrapped element set
aware that you need to enter valid syntax, as well as expressions that result in a
jQuery wrapped set. Otherwise, you're going to be faced with a handful of unhelp-
ful JavaScript errors.
jQuery wrapped set. Otherwise, you're going to be faced with a handful of unhelp-
ful JavaScript errors.
We'll see this new Lab in action as we work our way through the sections
that follow.
2.3.1 Determining the size of the wrapped set
We mentioned before that the set of jQuery wrapped elements acts a lot like an
array. This mimicry includes a
array. This mimicry includes a
length
property, like JavaScript arrays, that con-
tains the number of wrapped elements.
Should we wish to use a method rather than a property, jQuery also defines
the
size()
method, which returns the same information.
Consider the following statement:
$('#someDiv')
.html('There are '+$('a').size()+' link(s) on this page.');
The inner jQuery wrapper matches all elements of type
<a>
and returns the num-
ber of matched elements using the
size()
method. This is used to construct a text
string, which is set as the content of an element with
id
of
someDiv
using the
html()
method (which we'll see in the next chapter).
The formal syntax of the
size()
command is as follows:
OK
, so now you know how many elements you have. What if you want to access
them directly?
2.3.2 Obtaining elements from the wrapped set
Usually, once we have a wrapped set of elements, we can use jQuery commands to
perform some sort of operation upon them; for example, hiding them all with
the
perform some sort of operation upon them; for example, hiding them all with
the
hide()
method. But there may be times when we want to get our hands on a
Command syntax: size
size()
Returns the count of elements in the wrapped set
Parameters
none
Returns
The element count
The element count