findElement :: Event

Event.findElement(event, tagName) -> Element Returns the first DOM element with a given tag name, upwards from the one on which the event occurred.

Sometimes, you’re not interested in the actual element that got hit by the event. Sometimes you’re interested in its “closest element,” (either the original one, or its container, or its container’s container, etc.), defined by its tag (e.g., <p>). This is what findElement is for.

The provided tag name will be compared in a case-insensitive manner.

If no matching element is found, the document itself (HTMLDocument node) is returned.

Example

Here’s a simple code that lets you click everywhere on the page and hides the closest-fitting paragraph around your click (if any).

Event.observe(document.body, 'click', function(event) {

var elt = Event.findElement(event, 'P');

if (elt != document)

$(elt).hide();

});

For more complex searches, you’ll need to get the actual element and use up on it, which lets you express your request with CSS syntax, and also search farther than the first match (plus, the result is extension-guaranteed):

Event.observe(document.body, 'click', function(event) {

// First element from event source with 'container' among its CSS classes

var elt = $(Event.element(event)).up('.container');

// Or: second DIV from the event source

// elt = $(Event.element(event)).up('div', 1);

// Or: second DIV with 'holder' among its CSS classes...

// elt = $(Event.element(event)).up('div.holder', 1);

elt.hide();

});

See also

If you’re looking for the element directly hit by the event, just use the element function.

Prototype API 1.5.0 - prototypejs.org