jQuery in Action

jQuery fundamentals
7
In programming parlance, this type of construct is termed a wrapper because it
wraps the matching element(s) with extended functionality. We'll use the term
jQuery wrapper or wrapped set to refer to this set of matched elements that can be
operated on with the methods defined by jQuery.
Let's say that we want to fade out all
<div>
elements with the
CSS
class
not-
LongForThisWorld
. The jQuery statement is as follows:
$("div.notLongForThisWorld").fadeOut();
A special feature of a large number of these methods, which we often refer to as
jQuery commands, is that when they're done with their action (like a fading-out
operation), they return the same group of elements, ready for another action. For
example, say that we want to add a new
CSS
class,
removed
, to each of the elements
in addition to fading them out. We write
$("div.notLongForThisWorld").fadeOut().addClass("removed");
These jQuery chains can continue indefinitely. It's not uncommon to find exam-
ples in the wild of jQuery chains dozens of commands long. And because each
function works on all of the elements matched by the original selector, there's no
need to loop over the array of elements. It's all done for us behind the scenes!
Even though the selected group of objects is represented as a highly sophisti-
cated JavaScript object, we can pretend it's a typical array of elements, if neces-
sary. As a result, the following two statements produce identical results:
$("#someElement").html("I have added some text to an element");
or
$("#someElement")[0].innerHTML =
"I have added some text to an element");
Because we've used an
ID
selector, only one element will match the selector. The
first example uses the jQuery method
html()
, which replaces the contents of a
DOM
element with some
HTML
markup. The second example uses jQuery to
retrieve an array of elements, select the first one using an array index of
0
, and
replace the contents using an ordinary JavaScript means.
If we want to achieve the same results with a selector that resulted in multiple
matched elements, the following two fragments would produce identical results:
$("div.fillMeIn")
.html("I have added some text to a group of nodes");
or


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.