Prototype: "element-id".$() instead of $('element-id')

D

drnicwilliams

[TUTORIAL]

The Prototype library gives us the $() operation for converting a DOM
element id into the DOM element: $('element-id'). It also appends a
bunch of functions to the resulting object.

Sometimes though, passing a string into the $() function doesn't read
well; and only makes Javascript code harder to read. For example:
$(window.button_list()[3]).hide()

Instead, it'd be nice to have normal chainability. I like the
following syntax: window.button_list()[3].$().hide().

That is, call the $() method on a string object, instead of passing the
string into the $() method.

Add this code into your application:

String.prototype.$ = function() {
return $(document.getElementById(this));
}
From article:
http://drnicwilliams.com/2006/09/11/prototype-call-dollar-on-string/
 
R

Richard Cornford

drnicwilliams said:
[TUTORIAL]

Very funny.
The Prototype library gives us the $() operation

It is a not an operation, - $ - is a function that is called with an
argument.

Instead, it'd be nice to have normal chainability. I like the
following syntax: window.button_list()[3].$().hide().

In what sense "more normal"? In javascript chaining like this is more
an exception than in any sense common.

String.prototype.$ = function() {
return $(document.getElementById(this));
<snip>

As in Prototype.js the - $ - function is a poorly named wrapper around
- document.getElementById - why is the argument to the - $ - function
the return value from - getElmenetById - here?

And can document.getElementById - be relied upon to carry out the
String object to string primitive type-conversation on its argument? It
would seem safer to do that conversion explicitly.

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top