By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,600 Members | 1,887 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,600 IT Pros & Developers. It's quick & easy.

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

P: n/a
[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/...lar-on-string/

Sep 11 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
drnicwilliams wrote:
[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.

<snip>
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.

<snip>
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.

Sep 11 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.