Java Reference
In-Depth Information
The
update()
method
replaces
all existing content within the element. The following code
updates the document's body with the
a
object, thereby replacing the existing content with the
<a/>
element:
$(document.body).update(a);
It's important to remember the distinction between the two methods; otherwise, you may experience
unexpected results in your web page.
removing an element
Prototype makes it easy to remove an element from the DOM; simply call the
remove()
method on
the element object you want to remove, like this:
a.remove();
using events
When you extend an
Element
object with the
$()
function, you gain access to its
observe()
method.
Like the native
addEventListener()
method, this registers an event listener for a DOM element,
and it accepts two arguments: the event name and the function to call when the event fires. For
example, the following code registers a
click
event listener that executes the
divClick()
function:
function divClick(event) {
// do something
}
$("myDiv").observe("click", divClick);
And as you saw earlier, you can also use the
Event.observe()
method. The following code achieves
the same results using
Event.observe()
:
function divClick(event) {
// do something
}
Event.observe("myDiv", "click", divClick);
This code is slightly different from the first time you saw
Event.observe()
because the first
argument, in this case, is a string. You can pass the
id
of an element or a DOM/BOM object as the
first argument to
Event.observe()
. This method is particularly useful for objects like
window
. You
cannot call
$(w i n d o w).o b ser v e()
because the browser will throw an error. Instead, you have to use
Event.observe()
.
Prototype doesn't emulate the W3C DOM event model. Instead, it extends the
event
objects of
legacy‐IE and standards‐compliant browsers to give you a set of utility methods to work with
event data.
For example, the
element()
method returns the event target (the
srcElement
property for
legacy‐IE, and the
target
property for W3C DOM browsers). The following code uses