Element

Extensions to Prototype’s Element class

Summary
Extensions to Prototype’s Element class
Swaps a given class name on an element to a different class name, with a check to work out which class name an element currenly has first.
Attempts to finds a parent for a given element that matches a partial selector string.
Checks if a given element has a given parent element in the DOM tree.

Functions

swapClassName

Element.swapClassName = function(element,
className1,
className2)

Swaps a given class name on an element to a different class name, with a check to work out which class name an element currenly has first.  That is, if the element is of class className1, that will be replaced by className2, and vice-versa.

Parameters

elementElement, the form element to swap class names on
className1String, the first class name
className2String, the second class name

Example

Element.swapClassName($('name'), "culprit", "valid");

findParent

Element.findParent = function(element,
selector)

Attempts to finds a parent for a given element that matches a partial selector string.  If the element itself matches the selector, it is returned instead.  This can be particularly useful in mouse event handlers, where the element that fires the event tends to be the deepest element in the DOM, and you want to update a containing element.

Parameters

elementElement, the base element to search from
selectorString, a partial selector to find a parent element (or the element itself if it matches).  This is partial in the sense that it is a specific tagName with className, and/or ID only

Example

function navItemOnMouseClick(event)
{
var element = Event.element(event);
var navItem = Element.findParent(element, "a.nav-item");
// now you can operate on the link, if for example there were span tags inside each link, which might be in "element"
}

hasParent

Element.hasParent = function(element,
parent)

Checks if a given element has a given parent element in the DOM tree.  This would generally be most useful in event handlers, when you don’t exactly know which element you’re dealing with.

Parameters

elementElement, the base element to search from
parentElement, the parent element to check for

Returns

Booleantrue, if parent is an ancestor of element, false otherwise

See Also: findParent

Element.swapClassName = function(element,
className1,
className2)
Swaps a given class name on an element to a different class name, with a check to work out which class name an element currenly has first.
Element.findParent = function(element,
selector)
Attempts to finds a parent for a given element that matches a partial selector string.
Element.hasParent = function(element,
parent)
Checks if a given element has a given parent element in the DOM tree.