As I promised, the second chapter from the book “jQuery in Action” (by Bear Bibeault and Yehuda Katz). As well as from the first chapter, I chose all the most delicious and interesting ;-)
I remind you that the first chapter can be read
here .
Chapter 2. Creating Nested Item Sets.
2.1 Sampling of elements.
2.1.1 Using CSS selectors.
JQuery uses standard CSS selectors. You probably know them. Here are some examples to refresh your knowledge:
')
•
a
- all links will be selected (
<a>
);
•
#someid
- the item with
id = someid
will be selected;
•
.someclass
- all elements of the class
someclass
will be selected;
•
a#someid.someclass
- a link with
id = someid
class
someclass
will be selected;
•
p a.someclass
- all references to the class someclass inside the paragraph (
<p>
) will be selected.
Thus, in order to use the selector in jQuery, it is enough to write it inside the
$()
construction known to us, for example like this:
$(“p a.someclass”)
2.1.2 Attribute selectors, children and containers.
These are more advanced selectors used to select child elements, elements following other DOM elements, and elements with attributes that satisfy certain conditions.
When using a
child selector, the parent and its direct child elements are separated by the
>
character, for example
p > a
If the link is nested in some intermediate element, it will not be selected.
Let's sort selectors by attributes (
attribute selectors ).
For example, we want to select all links pointing to third-party resources of our site. This is done like this:
a[href^=http://]
This selector points to all links whose href value begins with
http://
. The
^
symbol indicates that the search expression will be at the beginning of the line in which the search will be performed.
Another option attribute selector:
form[method]
The selector will select all
<form>
that have the
method
attribute specified.
In order to select a specific attribute value, compose the following expression:
input[type=text]
I think everything is clear.
The following example uses the search already familiar to us at the beginning of the line, only now we apply it to search for the attribute value:
div[title^=my]
So we will select all the
<div>
whose title starts with
my
.
What about the search at the end of the line? We look:
a[href$=.pdf]
With this selector, we will select all links to PDF files.
To search for a value anywhere in a line, do the following:
a[href*=jquery.com]
Guess? These will be any links to
jquery.com .
The following type of selector is the
container selector :
li:has(a)
This selector will select all
<li>
elements that contain
<a>
. You can use up to one level of attachments of such selectors:
li:has(p:has(a))
The following option will no longer work:
li:has(p:has(a:has(b)))
Below is a table of basic CSS selectors supported by jQuery.
Selector | Description |
---|
* | All items |
E | All elements E |
EF | All elements F following E |
E> F | All elements F, directly child for E |
E + F | All elements of F, immediately preceding E, with F and E brothers. |
E ~ F | All elements of F, preceding E, with F and E brothers. |
E: has (F) | All elements E that have at least one child element F |
EC | All elements are E of class C. To select all elements of class C, use the selector * .C |
E # I | All elements E with identifier I. To select all elements with identifier I, use the selector * # I |
E [A] | All elements of E with attribute A of arbitrary value |
E [A = V] | All elements of E with attribute A equal to V |
E [A ^ = V] | All elements of E with attribute A, whose value starts at V |
E [A $ = V] | All elements of E with an attribute A whose value ends in V |
E [A * = V] | All elements of E with an attribute A whose value contains V |
2.1.3 Selection by position.
Sometimes it is necessary to select elements by their position relative to other elements on the page. JQuery provides this.
We look:
a:first
This will select the first
<a>
element on the page.
p:odd
Such a selector will select all odd items on the page. Another variant:
p:even
will choose even.
The following table shows other examples of the selection of items by position in the document.
Selector | Description |
---|
: first | The first item on the page. li a:first returns the first link inside the li list item. |
: last | The last item on the page. |
: odd | All odd items on the page. |
: even | All even items on the page. |
: first-child | First child. li:first-child returns the first item in each list. |
: last-child | Last child. |
: only-child | Returns items that have one child at a time. |
: nth-child (n) | Returns the nth child element. For example, li:nth-child(2) will return the second element of each list. |
: nth-child (even | odd) | Even or odd child element. For example,: returns the even elements of each list. |
: nth-child (Xn + Y) | Returns a child element whose order is found by formula. If Y is 0, it can be omitted. The example will become clearer: li:nth-child(3n) returns elements 0, 3, 6, etc., li:nth-child(5n+1) returns elements 1,6,11, etc. |
: eq (n) | Returns the nth item. |
: gt (n) | Return an item after the nth item. |
: lt (n) | Returns the item before n-th. |
Such a nuance: the nth-child selector starts counting n from 1, except for nth-child (Xn + Y), which starts counting n from zero, while the other selectors in the table count elements from 0.
Example:
Item number | n | 5n | 5n + 2 |
---|
0 | n / a | n / a | |
one | + | | |
2 | + | | + |
3 | + | | |
four | + | | |
five | + | + | |
6 | + | | |
7 | + | | + |
eight | + | | |
9 | + | | |
ten | + | + | |
eleven | + | | |
12 | + | | + |
2.1.4 Using jQuery special selectors
CSS selectors are, of course, good, but sometimes we need to select specific elements, for example, all checkboxes marked by the user. For this jQuery offers to use the selector
:checked
. For example, in this form:
input:checked
Below is a table of such selectors.
Selector | Description |
---|
: animated | Selects the elements with which the animation is performed (more details will be given in Chapter 5). |
: button | Selects all buttons ( input[type=submit] , input[type=reset] , input[type=button] , or simply button ). |
: checkbox | Selects all checkboxes ( input[type=checkbox] ). |
: checked | Selects all checked checkboxes. |
: contains (foo) | Selects items containing foo text. |
: disabled | Selects all items with the disabled property. |
: enabled | Selects all items with the enabled property. |
: file | Selects file upload fields (input[type=file]) . |
: header | Selects all headers (from <h1> to <h6> ). |
: hidden | Selects all hidden items. |
: image | Selects all input of type image ( input[type=image] ). |
: input | Selects form elements ( input , select , textarea , button ). |
: not (filter) | Selects the elements inverse to the filter (more on this after the table). |
: parent | Selects all items that have non-empty children. |
: password | Selects fields to enter a password ( input[type=password] ). |
: radio | Selects radio elements ( input[type=radio] ). |
: reset | Selects a reset button ( input[type=reset] or button[type=reset] ). |
: selected | Selects all items with the selected property. |
: submit | Selects the form submit buttons ( input[type=submit] or button[type= submit] ). |
: text | Selects text fields only ( input[type=text] ). |
: visible | Selects only visible items. |
A combination of such selectors is allowed, for example:
:radio:checked
or
:checkbox:checked:enabled
To invert the filter, use the filter specified in the table
:not
:
input:not(:checkbox)
So we will select all
input
elements, except for checkboxes.
note that
div p: not (: hidden) - correct
div: not (p: hidden) - not correct.
2.2 Creating HTML.
Code creation is done through the
$()
function known to us in the first chapter. For example,
$(“<div></div>”)
If we want to create an empty
<div>
element, it can be made shorter:
$(“<div>”)
which is equivalent to
$(“<div></div>”)
or
$(“<div/>”)
.
At the same time in such a shortened way it is impossible to create full-fledged
<script>
elements.
2.3 Managing nested items.
In this section, we will learn how to perform elementary actions with nested elements.
2.3.1 Determining the size of the attachment.
The set of nested elements in jQuery is very similar to a JavaScript array. It even has a
length
property that contains the number of nested elements.
The
size()
method will help us find out this number. For example, let's count the number of links on a page:
$('#someDiv').html(' '+$('a').size()+' .');
In this case, the search took place inside the element with the identifier
#someDiv
.
html()
will be discussed in the next chapter, for now, accept it as it is.
2.3.2 Extracting elements from a set of attachments.
As mentioned earlier, the set of attachments is very similar to an array of JavaScript, so it is allowed to extract elements from the set by simple indexing of elements, for example:
$('img[alt]')[0]
will give us the first element of all
<img>
on the page with the
alt
attribute.
In addition, jQuery has a special
get()
function that performs the same action:
$('img[alt]').get(0)
If the index of the element is not specified, we obtain the entire set of elements.
And what if we need to perform the inverse operation - to find the index of a particular element? For this there is a function
index()
.
var n = $('img').index($('img#findMe'));
So we know the index of the image with the identifier
findMe
among all the images on the page.
If the item is not found, the function returns
-1
.
2.3.3 Changing kit sizes.
Adding items to a setTo begin with this example: we want to select all images that have an attribute
title
or
alt
. Let's do it like this:
$('img[alt],img[title]')
The same is done by the special
add()
method:
$('img[alt]').add('img[title]')
That is, the method connects the selectors together, combining them with logical
. Inside the
add()
method, there may be a selector string, an HTML code fragment (in this case, elements will be created and added to the set) or DOM elements (which will be added to the set). For example:
$('p').add('<div>, !</div>')
Filtering the contents of the setThe
not()
method allows to exclude an element from a set by any parameter.
Suppose we need to select all the images, except for those that have the text
alt
attribute
puppy . To do this, we write:
$('img[title]').not('[title*=puppy]')
It is worth noting that the element type is not passed to the
not()
method, but only the parameter by which the element should be excluded from the set (that is, we wrote
not('[title*=puppy]')
instead of
not('img[title*=puppy]')
).
What to do if you need to filter the set with some expression? For this, there is a
filter()
method that applies the function passed to it to each element of the set. For example, select all table entries that contain only numerical values:
$('td').filter(function(){return this.innerHTML.match(/^d+$/)})
If the function returns
false
, the item will be excluded from the set.
SubsettingSometimes there is a need to isolate some of our elements from our set based on their order in the set. For this, jQuery has a special
slice()
method that returns a new set of elements (while the old one remains unchanged). Its syntax is as follows:
slice(begin,end)
where
begin
is the number of the first element from which to start allocating a new subset (the numbering starts from 0), and
end
is the number of the element that is no longer included in the set (if you do not write it, the rest of the set is selected in the subset).
For example, select the first four elements of the set:
$('*').slice(0,4)
2.3.4 Creating sets based on relationships.
jQuery allows you to create a new set based on the old, based on the position of the nested element relative to others. The table below lists these methods and their description.
Selector | Description |
---|
children () | Returns a set of unique element children. |
contents () | Returns all child nodes in the element set (including text elements) or in the document content, if presented as a frame. |
next () | Will return a set of all subsequent unique element brothers. |
nextAll () | Will return all subsequent item brothers. |
parent () | Returns the unique direct parents of the item. |
parents () | Will return all the unique ancestors of the elements. |
prev () | Will return a set of all previous unique element brothers. |
prevAll () | Will return a set of all previous item brothers. |
siblings () | Will return a set of all unique element brothers. |
For example,
$('li').children()
will return to us a set of elements nested in
<li>
.
More details
here .
2.3.5. A few more ways to work with nested items.
The
find()
method returns a new set containing elements that satisfy the selector.
For example, select all
<cite>
quotes within the
<p>
paragraph from the set contained in the wrappedSet variable:
wrappedSet.find('p cite')
The
contains()
method will return to us the set of elements inside which the string passed to the method is contained. For example:
$('p').contains('Lorem ipsum')
The example will return to us a set of
<p>
elements containing the text
“Lorem ipsum” .
And the last method in this section helps to check whether the set contains at least one element corresponding to the selector passed to it.
The
is()
method returns
true
if at least one element matches or
false
if it does not match the selector. Example:
var hasImage = $('*').is('img');
Thus, the
hasImage
variable will be set to
true
if the page has an
<img>
element.
2.3.6 jQuery chain management.
JQuery has the ability to chain methods together, which allows us to perform efficient operations. Consider a couple of methods that will help us further manage these chains of methods.
For example, let's take the
clone()
method (more will be discussed in the next chapter, now we need it in order to see the capabilities of another method). This method creates a copy of the elements in the collection. Let's see the following example:
$('img').clone().appendTo('#somewhere');
As a result, two sets will be created: one of all
<img>
elements on the page, and the second of a copy of these elements. The
clone()
method will return this second set to us and the
appendTo()
method will be applied to it. And what if we want, for example, to change the class of the original set after it is duplicated. That is, to do any action not with a copy, but with the original? After all, after the c
lone()
method, we will work with a copy.
In this situation, the
end()
method will come to our rescue. With it, we will switch back to working with the original set. See an example:
$('img').clone().appendTo('#somewhere').end().addClass('beenCloned');
In this case,
addClass()
will be applied to the original set, whereas without
end()
it would be applied to the clone.
And the last method in this chapter
andSelf()
, applies the method to the two preceding sets. A good example
from here (there is very little information in the book):
$("div").find("p").andSelf().addClass("border");
$("div").find("p").addClass("background");
We search for all
div
elements and all
p
elements inside them, and then assign them two class names. But pay attention, if in the first line we added the previous
div
to the set of
p
elements, then in the second line we added a class that defines the background color only for the
p
elements inside the
div
, but not for the
div
element itself.
That is the second chapter. Thank you for your attention, again I am waiting for comments, corrections, if something else did not correctly translate and, of course, critics.Also I remind you that you can always find these and the following articles in my blog , you can also go there ;-)