Event.observe function - observe element by class instead of id

14,459

$$ can retrieve elements by css selector, including by class via the period notation .:

$$('.myClass'); // array with all elements that have class "myClass"

To answer your question, Event.observe is the "static" version of observe (for all intents and purposes). As a convenience Prototype automagically makes .observe available off of all DOM elements (fetched with either $ or $$):

Examples:

// get one item by id with $ and attach an event listener:
$('myId').observe(eventName, handler);

// get many items by class with $$ and attach an event listener:
$$('.myClass').each(function(element) {
  element.observe(eventName, handler);
});

// or shorter:
$$('.myClass').invoke('observe', eventName, handler);
Share:
14,459
MTPy
Author by

MTPy

JEE,JSP,JSR-168 Portlets,Spring Batch,JPA

Updated on June 16, 2022

Comments

  • MTPy
    MTPy about 2 years

    There is prototype js function:

    Event.observe(element, eventName, handler)

    here the element means element's ID.

    Is it possible to put here element's class?

    I got this element from third party with class attribute only.