Section 10.2. DOM Manipulation


10.2. DOM Manipulation

In this section, we'll examine Prototype's classes and methods for manipulating the page elements.

10.2.1. $( )

The dollar function ($( )) is a specialized wrapper to the standard document.getElementById( ) DOM method. Like that method, $( ) returns the element with the given ID.

But unlike getElementById( ), you can pass more than one argument and $( ) will return an array with all the requested elements. And if an argument is anything other than a string, it will be passed through directly. As a result, you can safely call $( ) on a value multiple times. Whether the value is a string or already a DOM element, the output will be the same. For example:

// <p >One</p> // <p >Two</p> $('one').toString(  ); // => '[object HTMLParagraphElement]' $('one','two').toString(  ); // => [object P],[object P] $($('one')).toString(  ); // => [object HTMLParagraphElement]

10.2.2. $F( )

$F( element ) returns the value of any field input control, like a text box or a drop-down list. element can be either the ID string or the element object itself.

// <input type="text"  value="Joe Doe"> // <select > //   <option value="NY">New York</option> //   <option value="CA" selected="selected">California</option> // </select> $F('userName'); // => "Joe Doe" $F('state'); // => "CA"

10.2.3. Selectors

The Selector class (and its accompanying $$( ) method) allows you to reference page elements by their CSS selectorsthat is, using the same syntax that you would to identify elements in a CSS file.

Like the $( ) method, which takes one or more element IDs and returns references to those elements, the $$( ) method takes one or more CSS selector expressions and returns the matching elements. For example:

$$('form#foo input[type=text]').each(function(input) {   input.setStyle({color: 'red'}); });

$$( ) selects all of the text fields that descend from the form element with the ID foo. The elements are then looped over to have their styles changed. Examples of other possible expressions:

// By tag name, including wildcard $$('strong') $$('*') // By id and class $('#foo') $$('.bar') // By combinations of tag, id, and class $$('strong#foo') $$('string.bar') $$('string.bar.baz') $$('#foo.bar') $$('.bar#foo') $$('#foo.bar.baz') $$('strong#foo.bar') $$('strong.bar#foo') // By ancestors $$('#foo strong *') $$('strong#foo span') // By attribute existence $$('h1[class]') // By attribute value and negated value $$('a[href="#"]') $$('a[href!=#]') // By whitespace-tokenized attribute value $$('a[class~="internal"]') // By hyphen-tokenized attribute value $$('*[xml:lang|="es"]') // By multiple attribute conditions $$('a[class~=external][href="#"]') // Combining multiple expressions $('#foo', '#bar')

The Selector class provides a more thorough interface to Prototype's selector functionality.


initialize( expression )

Creates a new selector instance for expression.


findElements([ scope ])

Returns all elements that match the selector expression, that are children of the scope element (which defaults to the entire document).


match( element )

Returns true if element matches the selector expression.


toString( )

Returns a string representation of the selector expression.


matchElements( elements , expression )

Static method that returns the subset of elements that matches expression.


findElement( elements , expression [, index ])

Static method that returns the first element of elements that matches expression. If index is given, returns the nth matching element.


findChildElements( element , expressions )

Static method that returns an array of elements descending from element that match any expression in the expressions array.

10.2.3.1. Examples
// Create a Selector instance fooFinder = new Selector('.foo'); // Find all elements in the document with the class 'foo' fooFinder.findElements(  ); // Find all elements within the 'container' element with the class 'foo' fooFinder.findElements($('container')); // Determine whether the 'bar' element has the class 'foo' fooFinder.match($('bar')); // Find all elements with class 'foo' from the descendants of 'container' Selector.matchElements($('container').descendants(  ), '.foo'); // Find the first element with the class 'foo' from the descendants of 'container' Selector.findElement($('container').descendants(  ), '.foo'); // Find the second element with the class 'foo' from the descendants of 'container' Selector.findElement($('container').descendants(  ), '.foo', 1); // Find all elements with the class 'foo' within 'container' Selector.findChildElements($('container'), ['.foo']); // Find all elements with the class 'foo' or the class 'bar' within 'container' Selector.findChildElements($('container'), ['.foo', '.bar']);

10.2.3.2. document.getElementsByClassName(className [, parentElement])

Returns all the elements that are associated with the CSS class className. If no parentElement is given, the entire document body will be searched.

10.2.4. Element Methods

Provides methods for manipulating page elements. These methods can be accessed in two ways: first, as functions, for example:

Element.toggle('target'); var myElement = $('target2'); Element.update(myElement, 'Hello');

The above example toggles the visibility of the element with the ID foo and then replaces the contents of the element referenced by the variable myElement.

Alternatively, they can be accessed as methods on page element objects directly. The trick is that every time an element is referenced via Prototype's $( ) or $$( ) functions, all of the methods in Element.Methods are copied into the element object. So the above example could also be expressed as:

$('target').toggle(  ); var myElement = $('target2'); myElement.update('Hello');

Note how calling the methods in this way makes the first argument implicitwhat was update(myElement, 'Hello') becomes simply update('Hello').

Also note that many of these methods return the element that they act on, enabling convenient chaining. For example:

$('target').update('Hello').addClassName('big').show(  );

The methods:


hide( element )

Hides element by setting its display style to 'none'. Returns element.

$('target').hide(  ); Element.hide('target'); ['target', 'foo', 'bar'].each(Element.hide);


show( element )

Shows element by resetting its display style to ''. Returns element.

$('target').show(  ); Element.show('target'); ['target', 'foo', 'bar'].each(Element.show);


toggle( element )

Toggles the visibility of element. Returns element.

$('target').toggle(  );


visible( element )

Returns a Boolean value indicating whether the element is visible.

$('target').visible(  ); // => true


empty( element )

Returns a Boolean value indicating whether element's tag is empty (or has only whitespace).

$('target').empty(  ); // => false


remove( element )

Removes element from the document. Returns element.

$('target').remove(  );


update( element , html )

Replaces the inner html of element with the html. If the html contains <script> blocks they will not be included, but they will be evaluated. Returns element.

$('target').update('Hello'); $('target').update(  ) // clears the element $('target').update(123) // set element content to '123'


replace( element , html )

A cross-browser implementation of the "outerHTML" property; replaces the entire element (including its start and end tags) with html. Returns element.

$('target').replace('<p>Hello</p>');


classNames( element )

Returns an Element.ClassNames object representing the CSS class names associated with element.

$('target').classNames(  );


hasClassName( element , className )

Returns TRue if element has className as one of its class names.

$('target').hasClassName('foo'); // => false


addClassName( element , className )

Adds className to the list of CSS class names associated with element. Returns element.

$('target').addClassName('foo');


removeClassName( element , className )

Removes className from the list of CSS class names associated with element. Returns element.

$('target').removeClassName('foo');


getStyle( element , cssProperty )

Returns the value of the CSS property cssProperty (in either 'prop-name' or 'propName' format) in the element or null if not present.

$('target').getStyle('visibility'); // => 'visible'


setStyle( element , cssPropertyHash )

Sets the value of the CSS properties in element, according to the values in the cssPropertyHash hash. Returns element.

$('target').setStyle({visibility:'hidden'});


readAttribute( element , name )

Returns the value of element's attribute named name. Useful in conjunction with Enumerable.invoke for extracting the values of a custom attribute from a collection of elements.

// <div > //   <div  widget_>...</div> //   <div  widget_>...</div> //   <div  widget_>...</div> // </div> $$('div.widget').invoke('readAttribute', 'widget_id') // ["7", "8", "9"]


getDimensions( element )

Returns the dimensions of element. The returned value is an object with two properties: height and width.

$('target').getDimensions(  ).width; $('target').getDimensions(  ).height;


getHeight( element )

Returns the offsetHeight of element.


makeClipping( element )

Sets element's overflow style to hidden, saving the previous value. Returns element.

$('target').makeClipping(  );


undoClipping( element )

Sets element's overflow style back to its previous state. Returns element.

$('target').undoClipping(  );


makePositioned( element )

Sets element's position style to relative. Returns element.

$('target').makePositioned(  );


undoPositioned( element )

Sets element's position style to ''. Returns element.

$('target').undoPositioned(  );


scrollTo( element )

Scrolls the window to element's position. Returns element.

$('target').scrollTo(  );


cleanWhitespace( element )

Removes any whitespace text node children of element. Returns element.

$('target').cleanWhitespace(  );


ancestors( element )

Returns an array of all ancestor elements of element.

$('target').ancestors(  );


descendants( element )

Returns an array of all descendant elements of element.

$('target').descendants(  );


immediateDescendants(element)

Returns an array of element's child nodes without text nodes.

$('target').immediateDescendants(  );


siblings( element )

Returns an array of all sibling elements of element.

$('target').siblings(  );


previousSiblings( element )

Returns an array of all sibling elements of element before it in the tree.

$('target').previousSiblings(  );


nextSiblings( element )

Returns an array of all sibling elements of element after it in the tree.

$('target').nextSiblings(  );


up( element [, expression ][, index ])

Returns the first ancestor element of element that optionally matches the CSS selector expression. If index is given, returns the nth matching element.

$('target').up(  ); $('target').up(1); $('target').up('li'); $('target').up('li', 1);


down( element [, expression ][, index ])

Returns the first child element of element that optionally matches the CSS selector expression. If index is given, returns the nth matching element.

$('target').down(  ); $('target').down(1); $('target').down('li'); $('target').down('li', 1);


previous( element [, expression ][, index ])

Returns the first previous sibling element of element that optionally matches the CSS selector expression. If index is given, returns the nth matching element.

$('target').previous(  ); $('target').previous(1); $('target').previous('li'); $('target').previous('li', 1);


next( element [, expression ][, index ])

Returns the first next sibling element of element that optionally matches the CSS selector expression. If index is given, returns the nth matching element.

$('target').next(  ); $('target').next(1); $('target').next('li'); $('target').next('li', 1);


getElementsByClassName( element, className )

Returns an array of all descendants of element that have the class className.

$('target').getElementsByClassName('foo');


getElementsBySelector( element, expression1[, expression2 [...] )

Returns an array of all descendants of element that match the any of the given CSS selector expressions.

$('target').getElementsBySelector('.foo'); $('target').getElementsBySelector('li.foo', 'p.bar');


recursivelyCollect( element , property )

Returns an array of all elements related to element according to property, recursively.

// returns all ancestors of target  $('target').recursivelyCollect('parentNode');


match( element, selector )

Takes a single CSS selector expression (or Selector instance) and returns true if it matches element.

$('target').match('div'); // => true


childOf( element, ancestor )

Returns true if element is a descendant of ancestor.

$('target').childOf($('bar')); // => false


observe( element, name, observer [ , useCapture ])

Adds an event handler function observer to element for the event named name (e.g., 'click', 'load', etc.). If useCapture is true, the event is handled in the capture phase; if false it's handled in the bubbling phase. Returns element.

var greet=function(  ) { alert('Hi'); }; $('target').observe('click', greet);


stopObserving( element, name, observer [ , useCapture ])

Removes an event handler named name from element. observer is the function reference (not an anonymous function). If useCapture is true, the event is handled in the capture phase; if false it's handledin the bubbling phase. Returns element.

$('target').stopObserving('click', greet);


hasAttribute( element , attribute )

Returns true if element has an attribute named attribute.

// <div  foo="bar"></div> $('target').hasAttribute('foo'); // => true


inspect( element )

Returns a string representation of element useful for debugging, including its name, ID, and classes.

$('target').inspect(  ); // => '<div >'

The Form object provides additional element methods specifically for working with forms. As with Element.Methods, these methods are automatically added to elements accessed via $( ) and $$( ), but only if the element is a form.


serialize( element )

Returns a URL-formatted string of element's field names and values.

// <form ><input type="text" name="foo" value="bar" /></form> Form.serialize('target'); // => "foo=bar"


serializeElements( elements )

Returns a URL-formatted string of element's field names and values.

// <form ><input type="text" name="foo" value="bar" /></form> $('target').serializeElements(  ); // => "foo=bar"


findFirstElement( element )

Returns the first enabled field element in element.

$('target').findFirstElement(  );


getElements( element )

Returns an array containing all the input fields in element.

$('target').getElements(  );


getInputs( element [, typeName [, name ]])

Returns an array containing all the <input> elements in element. Optionally, the list can be filtered by the typeName or name attributes of the elements.

$('target').getInputs(  ); $('target').getInputs('text'); $('target').getInputs('text', 'foo');


disable( element )

Disables all the input fields in the form. Returns element.

$('target').disable(  );


enable( element )

Enables all the input fields in the form. Returns element.

$('target').enable(  );


focusFirstElement( element )

Activates the first visible, enabled input field in the form. Returns element.

$('target').focusFirstElement(  );


reset( element )

Resets the form to its default state. Returns element.

$('target').reset(  );

The Form.Element object (aliased as Field) provides additional element methods specifically for working with form fields. As with Element.Methods, these methods are automatically added to elements accessed via $( ) and $$( ), but only if the element is a form field.


serialize( element )

Returns element's name=value string.

// <input  type="text" name="foo" value="bar" /> $('target').serialize(  ); // => "foo=bar"


getValue( element )

Returns the value of element.

// <input  type="text" name="foo" value="bar" /> $('target').getValue(  ); // => "bar"


clear( element )

Clears the value of element. Returns element.

$('target').clear(  );


present( element )

Returns true if element contains a nonempty value.

// <input  type="text" name="foo" value="bar" /> $('target').present(  ); // => true


focus( element )

Moves the input focus to element. Returns element.

$('target').focus(  );


select( element )

Selects the value in element that supports text selection. Returns element.

$('target').select(  );


activate( element )

Moves the focus and selects the value in element that supports text selection. Returns element.

$('target').activate(  );


disable( element )

Disables input for element. Returns element.

$('target').disable(  );


enable( element )

Disables input for element. Returns element.

$('target').enable(  );

10.2.5. class Element.ClassNames

class element.classNames represents the collection of CSS class names associated with an element.


initialize( element )

Creates an Element.ClassNames object representing the CSS class names of element.


add( className )

Includes className in the list of class names associated with the element.


remove( className )

Removes className from the list of CSS class names associated with the element.


set( className )

Associates the element with className, removing any other class names from the element.

In addition to the methods listed here, Element.ClassNames is also extended by the Enumerable methods.

10.2.6. Inserting Content

Abstract.Insertion is used as the base class for the other classes that will provide dynamic content insertion.


initialize( element , content )

Creates an object that will help with dynamic content insertion.


adjacency

A string that specifies where the content will be placed relative to the given element. The possible values are: 'beforeBegin', 'afterBegin', 'beforeEnd', and 'afterEnd'.


element

The element object that the insertion will be made relative to.


content

The content to be inserted.

10.2.6.1. class Insertion.Before

Inherits from Abstract.Insertion. Initializing inserts content before element.

10.2.6.2. class Insertion.Top

Inherits from Abstract.Insertion. Initializing inserts content as the first child under element; i.e., after the opening tag of element.

10.2.6.3. class Insertion.Bottom

Inherits from Abstract.Insertion. Initializing inserts content as the last child under element; i.e., before element's closing tag.

10.2.6.4. class Insertion.After

Inherits from Abstract.Insertion. Initializing inserts content after element's closing tag.

10.2.6.5. Examples
// <span >Douglas</span> new Insertion.Before('name', 'Hello, '); new Insertion.Top('name', 'Scott '); new Insertion.Bottom('name', ' Raymond'); new Insertion.After('name', '.');

10.2.7. Element Positioning

The Position object provides a host of functions that help when working with element positioning.


prepare( )

Adjusts the deltaX and deltaY properties to accommodate changes in the scroll position. Remember to call this method before any calls to withinIncludingScrolloffset after the page scrolls.


realOffset( element )

Returns an array [left, top] with the scroll offsets of element, including any scroll offsets that affect it.


cumulativeOffset( element )

Returns an array [left, top] with the sum of the positioning offsets of element and all its ancestor elements.


positionedOffset( element )

Returns an array [left, top] with the sum of the positioning offsets of element and its ancestor elements up to the first ancestor with an absolute or relative position.


offsetParent( element )

Returns the nearest ancestor of element that has a position style other than static.


within( element , x , y )

Tests if the given point coordinates x and y are inside the bounding rectangle of element.


withinIncludingScrolloffsets( element , x , y )

Tests if the given point coordinates x and y are inside the bounding rectangle of element, accounting for scroll offsets.


overlap( mode , element )

mode should be 'vertical' or 'horizontal'. within( ) needs to be called right before calling this method. This method will return a decimal number between 0.0 and 1.0 representing the fraction of the coordinate that overlaps on the element. As an example, if the element is a square DIV with a 100px side and positioned at (300, 300), then within(divSquare, 330, 330); overlap('vertical', divSquare); should return 0.70, meaning that the point is at the 70 percent (100px 30px = 70px) mark from the bottom border of the DIV. The easiest way to understand it is to think of the given coordinate pair as the top-left corner of another rectangle, overlapping the first one. The number will be the percentage of the width or height that is overlapped (assuming that the second rectangle is large enough).


page( element )

Returns an array [left, top] with the offset of element relative to the viewport.


clone( source , target )

Resizes and repositions the element target identically to source.


absolutize( element )

Sets element's position style to absolute, preserving its position and size.


relativize( element )

Sets element's position style to relative, preserving its position and size.

10.2.8. Form Observers

The Abstract.TimedObserver class is used as the base class for the other classes that will monitor an element for changes to a property. Subclasses can be created to monitor things such as the input value of an element, one of the style properties, the number of rows in a table, etc. Derived classes implement getValue( ) to determine the current value being monitored in the element.


initialize( element , frequency , callback )

Creates an object that will monitor element every frequency in seconds and call callback when the element changes.


element

The element object that is being monitored.


frequency

The interval in seconds between checks.


callback

A function conforming to Function ( Object , String ) to be called whenever the element changes. It will receive the element object and the new value.


lastValue

A string with the last value verified in the element.

Form.Element.Observer is an implementation of Abstract.TimedObserver that monitors the value of form input elements. Use this class when you want to monitor an element that does not expose an event that reports the value changes. If the element exposes an event, use Form.Element.EventObserver.


getValue( )

Returns element's value.

Form.Observer is an implementation of Abstract.TimedObserver that monitors any changes to any of a form's input elements. Use this class when you want to monitor a form that contains elements that do not expose an event that reports the value changes. If the form exposes an event, use Form.EventObserver.


getValue( )

Returns the serialization of all form's data.

The Abstract.EventObserver class is used as the base class for the other classes that execute a callback function whenever a value-changing event happens for an element. Multiple observers can be bound to the same element. The callbacks will be executed in the order they are assigned to the element. The triggering event is onclick for radio buttons and checkboxes, and onchange for text boxes in general and list boxes/drop-downs. Derived classes implement getValue( ) to determine the current value being monitored in the element.


initialize( element , callback )

Creates an object that will monitor element and call callback when the event happens.


element

The element object that is being monitored.


callback

A function conforming to Function ( Object , String ) to be called whenever the element changes. It will receive the element object and the new value.


lastValue

A string with the last value verified in the element.

Form.Element.EventObserver


getValue( )

Returns the element's value.


Form.EventObserver

An implementation of Abstract.EventObserver that monitors any changes to any data entry element contained in a form, using the elements' events to detect when the value changes. If the form contains elements that do not expose any event that reports changes, use Form.Observer.


getValue( )

Returns the serialization of all the form's data.




Ajax on Rails
Ajax on Rails
ISBN: 0596527446
EAN: 2147483647
Year: 2006
Pages: 103
Authors: Scott Raymond

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net