jQuery in Action

Manipulating element properties and attributes
51
For the most part, the name of a JavaScript attribute property matches that of
any corresponding attribute, but there are some cases where they differ. For
example, the
class
attribute in this example is represented by the
className
attribute property.
jQuery gives us the means to easily manipulate an element's attributes and
gives us access to the element so that we can also change its properties. Which of
these we choose to manipulate depends on what we want to do and how we want
to do it.
Let's start by looking at getting and setting element properties.
3.1.1 Manipulating element properties
jQuery doesn't possess a specific command to obtain or modify the properties
of elements. Rather, we use the native JavaScript notation to access the proper-
ties and their values. The trick is in getting to the element references in the
first place.
The easiest way to inspect or modify the component elements of a matched set
is with the
each()
command. The syntax of this command is as follows:
This command can be used to easily set a property value onto all elements in a
matched set. For example, consider:
$('img').each(function(n){
this.alt='This is image['+n+'] with an id of '+this.id;
});
This statement will invoke the inline function for each image element on the
page, modifying its
alt
property using the order of the element and its
id
value.
Note that, because this is an attribute property tied to an attribute of the same
name, the
alt
attribute is also indirectly updated.
Command syntax: each
each(iterator)
Traverses all elements in the matched set invoking the passed iterator function for each.
Parameters
iterator
(Function) A function called for each element in the matched set. The parame-
ter passed to this function is set to the zero-based index of the element
within the set, and the element itself is available as the this property of the
function.
Returns
The wrapped set.


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

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