Prototype Element Methods More Convenient
Since we so recently published Dan Webb’s article on the Prototype library, it makes sense to continue tracking the evolution of the library here in this blog.
In the Prototype library, the Element
object (documentation) provides a bunch of methods that operate on a specified element in the document. Here’s the list of the most notable methods from the article:
var element = $('someId');
// Hides an element
Element.hide(element)
// Shows an element
Element.show(element)
// Adds a CSS class to the element
Element.addClassName(element, "cssClassName")
// Removes a CSS class from the element
Element.removeClassName(element, "cssClassName")
// Returns true if element has the CSS class
Element.hasClassName(element, "cssClassName")
// Returns {width: 123, height: 45}
Element.getDimensions(element)
// replaces the innerHTML of element with newHtml
Element.update(element, newHtml)
For a library designed to reduce the pain of writing JavaScript, this stuff was actually fairly verbose. But designer/developer JasonJustin Palmer has the scoop on some changes that are in the pipeline. Before long, you’ll be able to write the above method calls like this instead:
var element = $('someId');
element.hide()
element.show()
element.addClassName("cssClassName")
element.removeClassName("cssClassName")
element.hasClassName("cssClassName")
element.getDimensions()
element.update(newHtml)
Prototype’s handy $
function, which can fetch any element given its ID, will now enhance that element with the methods of the Element
object before returning it to you. The same goes for the $$
and getElementsByClassName
methods provided by Prototype.
The catch at this stage is that element references obtained by other means (i.e. through standard DOM collections/methods) will not be enhanced in this way, so you’ll have to be aware of which element references were generated by Prototype and which are standard DOM references — a significant break from tradition for Prototype. In fact, even some element references returned by Prototype methods (e.g. Form.getElements
) at this stage will still return “vanilla” DOM element references without the enhancements above.
Developers who aren’t keen on these inconsistencies may want to stick to the more verbose original syntax, but there are significant savings in typing for those developers who make heavy use of Prototype’s enhanced element fetching functions. For example:
$('someId').show();
This new functionality will make its debut in the upcoming release of Prototype 1.5. In the meantime, you can grab the latest work-in-progress version from Rails to try it out.