473,386 Members | 2,078 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Replacing document.getElementById with $ (dollar sign)

I've seen a few frameworks use the following:

function $(id) { return document.getElementById(id); }

Then to use:

$('something').innerHTML = 'blah';

I'm just trying to roll this out to my site and so far doing this has
saved about 8KB of javascript (lots of ajax/dynamic elements). I just
want to know whether there's any browser problems with doing this?
I've tested it on IE7, FF2, Safari 3 and IE6 and can't see any
problems. Are there any browsers that this won't work on?

Thanks
Jun 27 '08 #1
29 19112
On May 28, 8:47 am, Nick <nick.lemou...@gmail.comwrote:
I've seen a few frameworks use the following:

function $(id) { return document.getElementById(id); }

Then to use:

$('something').innerHTML = 'blah';

I'm just trying to roll this out to my site and so far doing this has
saved about 8KB of javascript (lots of ajax/dynamic elements). I just
want to know whether there's any browser problems with doing this?
I've tested it on IE7, FF2, Safari 3 and IE6 and can't see any
problems. Are there any browsers that this won't work on?
The $ character is valid anywhere in a javascript identifier.
However, its purpose is to signify machine generated code and
therefore should be reserved for that. The ECMAScript specification
section 7.6 states:

"The dollar sign is intended for use only in mechanically
generated code."
Some libraries use it as the name of a function that implements
functionality similar to getElementById, but also to do other things -
they are not simple wrappers for getElementById.

Therefore you can expect issues if you use $ as an identifier and your
code must co-exist with one of those libraries.

Saving 8kb by replacing document.getElementById with $ indicates to me
that you may be over-using it. If you really do need to use it
hundreds of times, you might consider some other abbreviated name.
Also, having your web server zip files for download will provide a
similar (though possibly not equivalent) reduction in size.
--
Rob
Jun 27 '08 #2
On May 27, 4:32 pm, RobG <rg...@iinet.net.auwrote:
On May 28, 8:47 am, Nick <nick.lemou...@gmail.comwrote:
I've seen a few frameworks use the following:
function $(id) { return document.getElementById(id); }
Then to use:
$('something').innerHTML = 'blah';
I'm just trying to roll this out to my site and so far doing this has
saved about 8KB of javascript (lots of ajax/dynamic elements). I just
want to know whether there's any browser problems with doing this?
I've tested it on IE7, FF2, Safari 3 and IE6 and can't see any
problems. Are there any browsers that this won't work on?

The $ character is valid anywhere in a javascript identifier.
However, its purpose is to signify machine generated code and
therefore should be reserved for that. The ECMAScript specification
section 7.6 states:

"The dollar sign is intended for use only in mechanically
generated code."

Some libraries use it as the name of a function that implements
functionality similar to getElementById, but also to do other things -
they are not simple wrappers for getElementById.
The result of a method named - $ - cannot be naturally expected
because - $ - does not have a clear meaning (at least not yet). The
general meaning seems to be "get an element from a string, or if it's
already an element, just return the element."

This is unnecessary delegation. It's going to slow things down, for
one:-

function $(id) { return document.getElementById(id); }

$("aDiv") results in two function calls, but:-

document.getElementById("aDiv");

- is only one function call.

The extra delegation introduces complexity into the program for the
benefit of making the code more compact.

Garrett
--
Rob
Jun 27 '08 #3
On May 28, 11:07 am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 27, 4:32 pm, RobG <rg...@iinet.net.auwrote:
On May 28, 8:47 am, Nick <nick.lemou...@gmail.comwrote:
I've seen a few frameworks use the following:
function $(id) { return document.getElementById(id); }
Then to use:
$('something').innerHTML = 'blah';
I'm just trying to roll this out to my site and so far doing this has
saved about 8KB of javascript (lots of ajax/dynamic elements). I just
want to know whether there's any browser problems with doing this?
I've tested it on IE7, FF2, Safari 3 and IE6 and can't see any
problems. Are there any browsers that this won't work on?
The $ character is valid anywhere in a javascript identifier.
However, its purpose is to signify machine generated code and
therefore should be reserved for that. The ECMAScript specification
section 7.6 states:
"The dollar sign is intended for use only in mechanically
generated code."
Some libraries use it as the name of a function that implements
functionality similar to getElementById, but also to do other things -
they are not simple wrappers for getElementById.

The result of a method named - $ - cannot be naturally expected
because - $ - does not have a clear meaning (at least not yet). The
general meaning seems to be "get an element from a string, or if it's
already an element, just return the element."

This is unnecessary delegation. It's going to slow things down, for
one:-

function $(id) { return document.getElementById(id); }
To do as specified above, it needs something like:

function $(id) {
return (typeof id == 'string')? document.getElementById(id) : id;
}
at least. Some such functions take multiple arguments and some take
CSS selectors too, so there is far more cruft in there than might be
expect.

But the $ character is used (abused?) more widely than that, in some
cases it seems to indicate a core function of a library - Prototype.js
has $, $$, $A, $F and so on. MooTools has $, $extend, $type, etc.

jQuery uses $ as an alias for the jQuery object, so it represents not
just getElementById but the entire library (more or less). The
project I am working on uses it as a character in machine generated
IDs and names (heaven forbid!).

So no particular meaning can be inferred from the use of $ outside of
the project context it is being used in.

$("aDiv") results in two function calls, but:-

document.getElementById("aDiv");

- is only one function call.
Also, where $ represents a function that implements CSS selectors, the
call is something like:

$('#id');
The argument must first be parsed to determine the selector before an
appropriate use is made of it. Hopefully XPath can be used where
supported to get some speed back, but for UAs sans XPath, a fall back
to standard DOM methods with filtering must be used.
--
Rob
Jun 27 '08 #4
On May 27, 6:07 pm, dhtml <dhtmlkitc...@gmail.comwrote:
On May 27, 4:32 pm, RobG <rg...@iinet.net.auwrote:
On May 28, 8:47 am, Nick <nick.lemou...@gmail.comwrote:
I've seen a few frameworks use the following:
function $(id) { return document.getElementById(id); }
Then to use:
$('something').innerHTML = 'blah';
I'm just trying to roll this out to my site and so far doing this has
saved about 8KB of javascript (lots of ajax/dynamic elements). I just
want to know whether there's any browser problems with doing this?
I've tested it on IE7, FF2, Safari 3 and IE6 and can't see any
problems. Are there any browsers that this won't work on?
The $ character is valid anywhere in a javascript identifier.
However, its purpose is to signify machine generated code and
therefore should be reserved for that. The ECMAScript specification
section 7.6 states:
"The dollar sign is intended for use only in mechanically
generated code."
Some libraries use it as the name of a function that implements
functionality similar to getElementById, but also to do other things -
they are not simple wrappers for getElementById.

The result of a method named - $ - cannot be naturally expected
because - $ - does not have a clear meaning (at least not yet). The
general meaning seems to be "get an element from a string, or if it's
already an element, just return the element."

This is unnecessary delegation. It's going to slow things down, for
one:-

function $(id) { return document.getElementById(id); }

$("aDiv") results in two function calls, but:-

document.getElementById("aDiv");

- is only one function call.

The extra delegation introduces complexity into the program for the
benefit of making the code more compact.

Garrett
--
Rob
If he's saved 8k, that's probably a much bigger deal to him than the
incredibly slight overhead of an extra function call per invocation
(that call is almost surely overwhelmed by the code being called--he
could check with a profiler, of course).

If his site is popular, that 8k not being served over and over means
quite a lot.
Jun 27 '08 #5
timothytoe meinte:
On May 27, 6:07 pm, dhtml <dhtmlkitc...@gmail.comwrote:
>The extra delegation introduces complexity into the program for the
benefit of making the code more compact.
If he's saved 8k, that's probably a much bigger deal to him than the
incredibly slight overhead of an extra function call per invocation
(that call is almost surely overwhelmed by the code being called--he
could check with a profiler, of course).
Saving 8kB on replacing "document.getElementById" by "$", means he calls
this method no less than 400(!) times. I'd go and check my sources first.
If his site is popular, that 8k not being served over and over means
quite a lot.
No, it means nothing. For example, splitting up the JS code into smaller
files means more HTTP requests, and _that's_ costly. But the extra 8kB
is even on a modem connection less than 2 extra seconds. And since one
could easily serve the files gzipped you'll finally end up with another
100-odd bytes of additional size.

Gregor
--
http://photo.gregorkofler.at ::: Landschafts- und Reisefotografie
http://web.gregorkofler.com ::: meine JS-Spielwiese
http://www.image2d.com ::: Bildagentur für den alpinen Raum
Jun 27 '08 #6
On May 28, 8:53 am, timothytoe <timothy...@gmail.comwrote:
On May 27, 6:07 pm, dhtml <dhtmlkitc...@gmail.comwrote:
On May 27, 4:32 pm, RobG <rg...@iinet.net.auwrote:
On May 28, 8:47 am, Nick <nick.lemou...@gmail.comwrote:
I've seen a few frameworks use the following:
function $(id) { return document.getElementById(id); }
Then to use:
$('something').innerHTML = 'blah';
I'm just trying to roll this out to my site and so far doing this has
saved about 8KB of javascript (lots of ajax/dynamic elements). I just
want to know whether there's any browser problems with doing this?
I've tested it on IE7, FF2, Safari 3 and IE6 and can't see any
problems. Are there any browsers that this won't work on?
The $ character is valid anywhere in a javascript identifier.
However, its purpose is to signify machine generated code and
therefore should be reserved for that. The ECMAScript specification
section 7.6 states:
"The dollar sign is intended for use only in mechanically
generated code."
Some libraries use it as the name of a function that implements
functionality similar to getElementById, but also to do other things -
they are not simple wrappers for getElementById.
The result of a method named - $ - cannot be naturally expected
because - $ - does not have a clear meaning (at least not yet). The
general meaning seems to be "get an element from a string, or if it's
already an element, just return the element."
This is unnecessary delegation. It's going to slow things down, for
one:-
function $(id) { return document.getElementById(id); }
$("aDiv") results in two function calls, but:-
document.getElementById("aDiv");
- is only one function call.
The extra delegation introduces complexity into the program for the
benefit of making the code more compact.
Garrett
--
Rob

If he's saved 8k, that's probably a much bigger deal to him than the
incredibly slight overhead of an extra function call per invocation
(that call is almost surely overwhelmed by the code being called--he
could check with a profiler, of course).
Calling a function is the second most expensive thing you can do in
JavaScript.
If his site is popular, that 8k not being served over and over means
quite a lot.
Local variables can also reduce the size, though not as many bytes are
saved. Example:

function blah() {
var d = document
x = d.getElementById("x"),
y = d.getElementById("y");
}

Additional benefits of this approach:
1) better performance, because the d variable is bound to the local
scope and
2) local variables with a longer identifier can be compressed using a
typical Rhino-based compression tool.

$ is not clearly defined as to what the expected outcome should be; $
is meaningless.

Looking at Prototype JS:

function $(element) {
if (arguments.length 1) {
for (var i = 0, elements = [], length = arguments.length; i <
length; i++)
elements.push($(arguments[i]));
return elements;
}
if (Object.isString(element))
element = document.getElementById(element);
return Element.extend(element);
}

At a minimum, each call to $ entails 1 call to isString, 1 call to
document.getElementById, and one call to Element.extend.

$..............................+1
+--document.getElementById....+1
+--Element.extend.............+1

3 calls so far. Looking at Object.extend:

Object.extend(function(element) {
if (!element || element._extendedByPrototype ||
element.nodeType != 1 || element == window) return element;

var methods = Object.clone(Methods),
tagName = element.tagName, property, value;

// extend methods for specific tags
if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);

for (property in methods) {
value = methods[property];
if (Object.isFunction(value) && !(property in element))
element[property] = value.methodize();
}

element._extendedByPrototype = Prototype.emptyFunction;
return element;

}

Object.extend calls clone, then ByTag, which recursively calls extend,
the element's methods are "methodized"

It gets a little more complicated than it appears. Prototype JS's $
does not return a DOM Element, but instead a DOM Element that is
wrapped with a Prototype JS Element.

So that's what $ means in Prototype JS, a very popular JavaScript
library. To use $ in another library would cause confusion among
developers who are accustomed to working with Prototype JS. I think
it's a bad idea.

Now the op's question title in this thread is: "Replacing
document.getElementById with $"

var $ = document.getElementById;
$("myg_popup");

Returns an element in IE and throws an Error in Firefox (this is
expected, but the error should probably be a TypeError).
Jun 27 '08 #7
dhtml wrote:
Now the op's question title in this thread is: "Replacing
document.getElementById with $"

var $ = document.getElementById;
$("myg_popup");

[...] throws an Error in Firefox
No, it does not, because with

try
{
$("myg_popup");
}
catch (e if e instanceof Error)
{
console.log(e);
}
catch (e)
{
console.log(e.name);
}

as supported by JavaScript 1.5+, console.log(e) never executes. It
does throw an exception, but obviously no Error. e.name also yields
"NS_ERROR_XPC_BAD_OP_ON_WN_PROTO", not "Error" as it would if the
exception was an native Error.
(this is expected, but the error should probably be a TypeError).
A TypeError exception would "[indicate] the actual type of an operand is
different than the expected type", and this is not the case here. Instead,
the method has been called on an incompatible object, the native Global
Object instead of a host Document object. There is no error type in
ECMAScript Ed. 3 to describe the situation properly except the generic
Error; however, even that was not used.
PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16
Jun 27 '08 #8
Gregor Kofler wrote:
timothytoe meinte:
>On May 27, 6:07 pm, dhtml wrote:
>>The extra delegation introduces complexity into the
program for the benefit of making the code more
compact.
If he's saved 8k, that's probably a much bigger deal
to him than the incredibly slight overhead of an extra
function call per invocation (that call is almost surely
overwhelmed by the code being called--he could check
with a profiler, of course).

Saving 8kB on replacing "document.getElementById" by
"$", means he calls this method no less than 400(!)
times. I'd go and check my sources first.
I make it nearer 350, But even that seems excessive. I did a text search
for ".getElementById" in the 150,000-odd lines of javascript source code
for a project that I work on and found 304 occurrences (with 141 of
those in a relatively small (8,000 line) sub-system that was externally
sourced and is, in my opinion, not particularly well written). Where
that project is concerned, I would not consider an 8k difference in the
size of the download as worth the effort (and certainly not worth the
(ongoing maintenance and debugging) cost in rendering the source code
obscure).
>If his site is popular, that 8k not being served over
and over means quite a lot.

No, it means nothing.
For one thing, the sensible arrangement for a external JS file is to
encourage its caching on the client, so if 'popular' relates to repeat
visits, for anyone returning there would be no need for the file to be
'served' at all.
For example, splitting up the JS code into smaller files means more
HTTP requests, and _that's_ costly.
But the extra 8kB is even on a modem connection less
than 2 extra seconds. And since one could easily serve
the files gzipped you'll finally end up with another 100-odd bytes of
additional size.
From what I understand of text compression techniques (which certainly
is not very detailed or in any depth) they often work by acting upon
repetition. Substituting one repetitious sequence of characters with a
shorter one will not alter the amount of repetition, and so the post
compression difference might be as little as the difference in length
between the two character sequences. So possibly as little as 23 bytes
post zip compression, with the source code for them added function call
more than negating that small gain (as it then contains the now
non-repeated - getElementById - character sequence).

Richard.

Jun 27 '08 #9
Richard Cornford meinte:
Gregor Kofler wrote:
>Saving 8kB on replacing "document.getElementById" by
"$", means he calls this method no less than 400(!)
times. I'd go and check my sources first.

I make it nearer 350, But even that seems excessive.
<nitpick>
8192/22 gives 372 plus a few more for the function/method to replace
document.gEBI()
</nitpick>
>>If his site is popular, that 8k not being served over
and over means quite a lot.

No, it means nothing.

For one thing, the sensible arrangement for a external JS file is to
encourage its caching on the client, so if 'popular' relates to repeat
visits, for anyone returning there would be no need for the file to be
'served' at all.
ACK.
>For example, splitting up the JS code into smaller files means more
HTTP requests, and _that's_ costly.
But the extra 8kB is even on a modem connection less
than 2 extra seconds. And since one could easily serve
the files gzipped you'll finally end up with another 100-odd bytes of
additional size.
I should have added, that with today's penchant for "Web 2.0" pages,
sporting plenty of graphics, JS, CSS, Flash, those 8kB are about as
"heavy" as a small background image for one menu entry...
From what I understand of text compression techniques (which certainly
is not very detailed or in any depth) they often work by acting upon
repetition. Substituting one repetitious sequence of characters with a
shorter one will not alter the amount of repetition, and so the post
compression difference might be as little as the difference in length
between the two character sequences. So possibly as little as 23 bytes
post zip compression, with the source code for them added function call
more than negating that small gain (as it then contains the now
non-repeated - getElementById - character sequence).
My own JS-"library", already "compressed" by Douglas Crockford's tool,
is gzipped about one quarter of the original 64kB. (It contains no more
than 4 gEBI() calls.)

Gregor
--
http://photo.gregorkofler.at ::: Landschafts- und Reisefotografie
http://web.gregorkofler.com ::: meine JS-Spielwiese
http://www.image2d.com ::: Bildagentur für den alpinen Raum
Jun 27 '08 #10
dhtml <dh**********@gmail.comwrites:
>>
If he's saved 8k, that's probably a much bigger deal to him than the
incredibly slight overhead of an extra function call per invocation
(that call is almost surely overwhelmed by the code being called--he
could check with a profiler, of course).

Calling a function is the second most expensive thing you can do in
JavaScript.
Do you know of some sort of 'benchmark site' where we could find metrics
about some common operations, on some of the most common
ecmascript/JavaScript/JScript implementations?

It's not that I don't believe you, but I realize that it might be
helpful to have hints on things such as:
- iterating over arrays yourself
(var i, n; for (i = 0, n = arr.length; i < n; i ++) {...})
- iterating over arrays with forEach () (for implementations that offer
it)
- iterating over objects with for-in
- calling functions
- making new objects with the "{}" literal
- ...

Of course, I also realize the value of such benchmarks, and that
they must _not_ be taken too seriously, but maybe they could give
advices about what practices to avoid at all costs...

A.
Jun 27 '08 #11
On May 28, 10:05*am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 28, 8:53 am, timothytoe <timothy...@gmail.comwrote:


On May 27, 6:07 pm, dhtml <dhtmlkitc...@gmail.comwrote:
On May 27, 4:32 pm, RobG <rg...@iinet.net.auwrote:

It gets a little more complicated than it appears. Prototype JS's $
does not return a DOM Element, but instead a DOM Element that is
wrapped with a Prototype JS Element.
<clarification>
It actually is a DOM Element that gets returned, but with other
properties added to it, depending on the tagName.
</clarification>

Garrett
Jun 27 '08 #12
In comp.lang.javascript message <b7a3a120-34f7-48e3-8668-2c51b052f0d4@h1
g2000prh.googlegroups.com>, Tue, 27 May 2008 15:47:32, Nick
<ni***********@gmail.composted:
>I've seen a few frameworks use the following:

function $(id) { return document.getElementById(id); }

Then to use:

$('something').innerHTML = 'blah';
For that, I use Wryt('something', 'blah') with

function Wryt(ID, S) { document.getElementById(ID).innerHTML = S }

in an Included file. It saves (where applicable) more bytes than yours
does, is easier to read, and avoids the contentious $. Some might
prefer, of course, to use "wryt" instead.
Given that 'blah', whatever it may contain, will generally cause the
browser to render text and/or interpret HTML, ISTM that ant overhead
associated with using such a function rather than handling 'blah' in
some other fashion will be insignificant.

--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/- FAQqish topics, acronyms & links;
Astro stuff via astron-1.htm, gravity0.htm ; quotings.htm, pascal.htm, etc.
No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.
Jun 27 '08 #13
VK
On May 30, 5:06 am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 28, 10:05 am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 28, 8:53 am, timothytoe <timothy...@gmail.comwrote:
On May 27, 6:07 pm, dhtml <dhtmlkitc...@gmail.comwrote:
On May 27, 4:32 pm, RobG <rg...@iinet.net.auwrote:
It gets a little more complicated than it appears. Prototype JS's $
does not return a DOM Element, but instead a DOM Element that is
wrapped with a Prototype JS Element.

<clarification>
It actually is a DOM Element that gets returned, but with other
properties added to it, depending on the tagName.
</clarification>
Still wrong ;-)

$ returns whatever document.getElementById would return. The trick is
that on Gecko browsers all DOM elements are claimed to be JavaScript
objects with the Object prototype underneath, just like Array, Date or
MyOwnObject would be. Technically it is of course not true, but this
is what prototype checks will report. I am still obscure of the reason
of such behavior: is it some WONTFIX bug or some forced model patch
for XBL accomodation?

Any way the phenomenon you are describing doesn't depend on $
implementation but on the browser you are testing with.

Jun 27 '08 #14
VK
On May 28, 3:32 am, RobG <rg...@iinet.net.auwrote:
On May 28, 8:47 am, Nick <nick.lemou...@gmail.comwrote:
I've seen a few frameworks use the following:
function $(id) { return document.getElementById(id); }
Then to use:
$('something').innerHTML = 'blah';
I'm just trying to roll this out to my site and so far doing this has
saved about 8KB of javascript (lots of ajax/dynamic elements). I just
want to know whether there's any browser problems with doing this?
I've tested it on IE7, FF2, Safari 3 and IE6 and can't see any
problems. Are there any browsers that this won't work on?

The $ character is valid anywhere in a javascript identifier.
However, its purpose is to signify machine generated code and
therefore should be reserved for that. The ECMAScript specification
section 7.6 states:

"The dollar sign is intended for use only in mechanically
generated code."

Some libraries use it as the name of a function that implements
functionality similar to getElementById, but also to do other things -
they are not simple wrappers for getElementById.

Therefore you can expect issues if you use $ as an identifier and your
code must co-exist with one of those libraries.
Fully sustaining the above statements I would also suggest to ban
further discussions of the kind "$ will save the world" or "$ is
evil". Strictly technically speaking $ or $foo or f$o or foo$ are
perfectly valid identifier so they never break a stay alone program.
Therefore "to use or not to use $" discussion without any specific 3rd
party library coexistence in mind are plain silly and fruitless. It
has all signs then of yet another endless rwar topic, same as say the
most suggested code pretty-print. This group so far didn't experience
the "brackets position rwar" disease roaming by C(++) and Java groups
and thanks to God, let it stay this way.
Yet this Javascript-specific "$ sign rwar" is still actively
propagated by some group regulars. My strictly IMHO opinion is that
has nothing to do with the quoted to death sentence in the paragraph
7.6 of ECMA 3rd. ed. It just happened that:
1) Javascript matured and respectively switched to frameworks paradigm
however one would hate to see it's happening.
2) The most prominent framework is misfortune to be at once the most
hated one by some regulars and at the same time using $ identifier.
IMHO 1) + 2) is the only reason that someone is ready to die for one
sentence side note in specs and nothing else. Am I write or not, I
suggest to anyone making rwar fun for side reader. I feel that many
regular readers have discovered by now: "if the NG gets boring, ask is
should I use $, then just enjoy".
NPOV answer for the "$ question" could be:
1) $ sign is a valid identifier in Javascript
2) section 7.6 of ECMA-262 3rd ed. says that:
"This standard specifies one departure from the grammar given in the
Unicode standard: The dollar sign ($) and the underscore (_) are
permitted anywhere in an identifier. The dollar sign is intended for
use only in mechanically generated code."
This way identifiers like $ or $foo or f$o or foo$ are fully valid but
not suggested by ECMA-262 3rd ed. for the clarity of the code origin.
3) ISO/IEC 16262:2002 sustains? / drops? / narrows? / extends?
ECMA-262 3rd ed. recommendation
I couldn't get a copy of ISO/IEC 16262:2002 - they used to charge for
papers but provide PDF for free download: but now they want US $235
for the download as well which is a scam to me. Anyone has a copy to
look at?
4) For the exact clarity of the recommendation in the section 7.6 it
would be most helpful to define "mechanically generated code" in
application to Javascript. In Java where the sentence in question is
coming from it referred to $SubClass1.class, $SubClass2.class etc.
separate package files automatically generated by javac for dependent
classes of the main class. What is "mechanically generated code" in
application to Javascript is not so far defined. This language doesn't
need code compilation before serving from the server so never had a
standard compiler with some standard documented behavior. This way
"mechanically generated code" has to be defined for Javascript
separately.
This way parts 3) and 4) of the suggested NPOV answer still need more
work.
5) Some currently widely used frameworks are using $ sign as a global
variable for different purposes. To name a few:
Prototype library is using $ sign as an extended version of
document.getElementById method with added argument check and some
other extra feature. This $ sign usage is the most frequent but it is
not a part of any standard nor should be expected for any given
library.
jQuery is using $ sign by default as a reference to the library object
itself. This makes the default jQuery behavior incompatible with
Prototype library and requires workarounds if both libraries are used
at once. For more details see: http://docs.jquery.com/Using_jQuery_...ther_Libraries
It means that the developers have to be careful with $ sign usage to
avoid possible name conflicts. They also have to careful with
different 3rd party libraries used together respectively checking the
presence and the actual usage of $ sign in each library.
Saving 8kb by replacing document.getElementById with $ indicates to me
that you may be over-using it. If you really do need to use it
hundreds of times, you might consider some other abbreviated name.
gEBI ? _ ? __ ? The options are endless but it is not the point. The
point 5) above is not caused by some special $ sign "namespace slash
capability". It is the side effect of any identifier being widely used
by many groups pf developers at once. Imagine gEBI became the most
suggested shortcut: then we'll have to issue the same warning about
gEBI.
Jun 27 '08 #15
On May 31, 5:27 am, VK <schools_r...@yahoo.comwrote:
On May 30, 5:06 am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 28, 10:05 am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 28, 8:53 am, timothytoe <timothy...@gmail.comwrote:
On May 27, 6:07 pm, dhtml <dhtmlkitc...@gmail.comwrote:
On May 27, 4:32 pm, RobG <rg...@iinet.net.auwrote:
It gets a little more complicated than it appears. Prototype JS's $
does not return a DOM Element, but instead a DOM Element that is
wrapped with a Prototype JS Element.
<clarification>
It actually is a DOM Element that gets returned, but with other
properties added to it, depending on the tagName.
</clarification>

Still wrong ;-)

$ returns whatever document.getElementById would return.
No, it doesn't. Whatever $ returns depends on the browser and what the
library has assumed has has been done to Host DOM interfaces'
prototypes.
The trick is
that on Gecko browsers all DOM elements are claimed to be JavaScript
objects with the Object prototype underneath, just like Array, Date or
MyOwnObject would be. Technically it is of course not true, but this
is what prototype checks will report.
There is no standard to support the author's assumption that
HTMLTableRowElement, or someNode.__proto__ will be an object, or that
modifying that object, that the properties will be resolved on DOM
nodes of corresponding tagNames. It doesn't work cross browser.
Relying on the __proto__ property is not guaranteed to be safe.

Element.extend uses a different approach used for other browsers. This
other approach is to add extra properties to the individual element
itself.

Element.extend either modifies the object itself or, if the author
assumes that the element's prototype, window["HTML" + tagName[trans] +
"Element"] has been modified by his modifications, then the element is
returned.

$ does not, in fact, return whatever document.getElementById would
return.
Any way the phenomenon you are describing doesn't depend on $
implementation but on the browser you are testing with.
Right.
Jun 27 '08 #16
VK
On Jun 1, 1:41 am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 31, 5:27 am, VK <schools_r...@yahoo.comwrote:
On May 30, 5:06 am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 28, 10:05 am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 28, 8:53 am, timothytoe <timothy...@gmail.comwrote:
On May 27, 6:07 pm, dhtml <dhtmlkitc...@gmail.comwrote:
On May 27, 4:32 pm, RobG <rg...@iinet.net.auwrote:
It gets a little more complicated than it appears. Prototype JS's $
does not return a DOM Element, but instead a DOM Element that is
wrapped with a Prototype JS Element.
<clarification>
It actually is a DOM Element that gets returned, but with other
properties added to it, depending on the tagName.
</clarification>
Still wrong ;-)
$ returns whatever document.getElementById would return.

No, it doesn't. Whatever $ returns depends on the browser and what the
library has assumed has has been done to Host DOM interfaces'
prototypes.
By saying "prototype" here we are of course referring to the generic
term meaning, like "an original type, form, or instance of something
serving as a typical example, basis, or standard for other things of
the same category". We do not mean the Javascript prototype as of say
Array.prototype or MyObject.prototype
DOM interfaces are not instances of Javascript Object nor they have
anything to do with it, whatever isProrotypeOf or instanceof checks
would report on some browsers.
The trick is
that on Gecko browsers all DOM elements are claimed to be JavaScript
objects with the Object prototype underneath, just like Array, Date or
MyOwnObject would be. Technically it is of course not true, but this
is what prototype checks will report.

There is no standard to support the author's assumption that
HTMLTableRowElement, or someNode.__proto__ will be an object, or that
modifying that object, that the properties will be resolved on DOM
nodes of corresponding tagNames. It doesn't work cross browser.
Relying on the __proto__ property is not guaranteed to be safe.
Not sure how did Netscape/Gecko __proto__ popped up into the picture.
I guess I missed some of previous posts. Of course no one should relay
on __proto__ property availability for cross-browser solutions.
Element.extend uses a different approach used for other browsers. This
other approach is to add extra properties to the individual element
itself.
The native DOM element interfaces get open for augmentation and
modification over XUL (Gecko) and behavior (IE). This way one can make
say all P element on the page able to play music or make XHR request.
It is a very powerful and flexible approach. Unfortunately minor
players are still late to implement either one so wherever Safari or
similar is in consideration one still has to use the prehistoric
element iteration with new properties assignment.
$ does not, in fact, return whatever document.getElementById would
return.
If we are talking about $ function as implemented in Prototype.js then
it is document.getElementById with argument check added, so yes, where
document.getElementById would error out, $ returns some meaningful
result. Where document.getElementById would work, $ returns what
document.getElementById does return.
Jun 27 '08 #17
On Jun 1, 6:17*pm, VK <schools_r...@yahoo.comwrote:
[...]
If we are talking about $ function as implemented in Prototype.js then
it is document.getElementById with argument check added, so yes, where
document.getElementById would error out, $ returns some meaningful
result.
No, it doesn't. It unconditionally calls document.getElementById if
the argument is a string. There is no feature check or attempt at any
kind of error handling, either for the call or what it returns,
therefore where document.getElementById will error, so will
Prototype.js's $ function.
--
Rob
Jun 27 '08 #18
VK
On Jun 1, 3:27 pm, RobG <rg...@iinet.net.auwrote:
On Jun 1, 6:17 pm, VK <schools_r...@yahoo.comwrote:
[...]
If we are talking about $ function as implemented in Prototype.js then
it is document.getElementById with argument check added, so yes, where
document.getElementById would error out, $ returns some meaningful
result.

No, it doesn't. It unconditionally calls document.getElementById if
the argument is a string. There is no feature check or attempt at any
kind of error handling, either for the call or what it returns,
therefore where document.getElementById will error, so will
Prototype.js's $ function.
document.getElementById(nonExistingID) should not error out neither:
it simply returns null (undefined?) so false in condition checks.
Prototype's $ adds argument check for being an object reference. This
way where document.getElementById(objectReference) would search for id
"[object Object]" or "HTMLParagraphElement" or similar, $ simply
echoing the argument back. Such method polymorphism can be considered
as handy or bad as error-hiding but it would be all different question
then.

Jun 27 '08 #19
VK wrote:
On Jun 1, 3:27 pm, RobG <rg...@iinet.net.auwrote:
>On Jun 1, 6:17 pm, VK <schools_r...@yahoo.comwrote:
[...]
>>If we are talking about $ function as implemented in Prototype.js then
it is document.getElementById with argument check added, so yes, where
document.getElementById would error out, $ returns some meaningful
result.
No, it doesn't. It unconditionally calls document.getElementById if
the argument is a string. There is no feature check or attempt at any
kind of error handling, either for the call or what it returns,
therefore where document.getElementById will error, so will
Prototype.js's $ function.

document.getElementById(nonExistingID) should not error out neither:
But it could.
it simply returns null (undefined?)
If it can be called.
PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16
Jun 27 '08 #20
On Jun 1, 4:27*am, RobG <rg...@iinet.net.auwrote:
On Jun 1, 6:17*pm, VK <schools_r...@yahoo.comwrote:
[...]
If we are talking about $ function as implemented in Prototype.js then
it is document.getElementById with argument check added, so yes, where
document.getElementById would error out, $ returns some meaningful
result.

No, it doesn't. *It unconditionally calls document.getElementById if
the argument is a string. *There is no feature check or attempt at any
kind of error handling, either for the call or what it returns,
therefore where document.getElementById will error, so will
Prototype.js's $ function.
There's a check in Element.extend:

var extend = Object.extend(function(element) {
if (!element || element._extendedByPrototype ||
element.nodeType != 1 || element == window) return element;

When the code reaches: if (!element

- it will return null, and element is null, then null (not undefined)
is returned.

Though it might have seemed more intuitive if the - if (!element) -
check had been done in the dollar function, prior to calling extend.
--
Rob
Jun 27 '08 #21
On Jun 1, 1:17*am, VK <schools_r...@yahoo.comwrote:
On Jun 1, 1:41 am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 31, 5:27 am, VK <schools_r...@yahoo.comwrote:
On May 30, 5:06 am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 28, 10:05 am, dhtml <dhtmlkitc...@gmail.comwrote:
On May 28, 8:53 am, timothytoe <timothy...@gmail.comwrote:
On May 27, 6:07 pm, dhtml <dhtmlkitc...@gmail.comwrote:
On May 27, 4:32 pm, RobG <rg...@iinet.net.auwrote:
It gets a little more complicated than it appears. Prototype JS's $
does not return a DOM Element, but instead a DOM Element that is
wrapped with a Prototype JS Element.
<clarification>
It actually is a DOM Element that gets returned, but with other
properties added to it, depending on the tagName.
</clarification>
Still wrong ;-)
$ returns whatever document.getElementById would return.
No, it doesn't. Whatever $ returns depends on the browser and what the
library has assumed has has been done to Host DOM interfaces'
prototypes.

By saying "prototype" here we are of course referring to the generic
term meaning, like "an original type, form, or instance of something
serving as a typical example, basis, or standard for other things of
the same category". We do not mean the Javascript prototype as of say
Array.prototype or MyObject.prototype
DOM interfaces are not instances of Javascript Object nor they have
anything to do with it, whatever isProrotypeOf or instanceof checks
would report on some browsers.
The trick is
that on Gecko browsers all DOM elements are claimed to be JavaScript
objects with the Object prototype underneath, just like Array, Date or
MyOwnObject would be. Technically it is of course not true, but this
is what prototype checks will report.
There is no standard to support the author's assumption that
HTMLTableRowElement, or someNode.__proto__ will be an object, or that
modifying that object, that the properties will be resolved on DOM
nodes of corresponding tagNames. It doesn't work cross browser.
Relying on the __proto__ property is not guaranteed to be safe.

Not sure how did Netscape/Gecko __proto__ popped up into the picture.
I guess I missed some of previous posts. Of course no one should relay
on __proto__ property availability for cross-browser solutions.
Element.extend uses a different approach used for other browsers. This
other approach is to add extra properties to the individual element
itself.

The native DOM element interfaces get open for augmentation and
modification over XUL (Gecko) and behavior (IE). This way one can make
say all P element on the page able to play music or make XHR request.
It is a very powerful and flexible approach. Unfortunately minor
players are still late to implement either one so wherever Safari or
similar is in consideration one still has to use the prehistoric
element iteration with new properties assignment.
$ does not, in fact, return whatever document.getElementById would
return.

If we are talking about $ function as implemented in Prototype.js then
it is document.getElementById with argument check added, so yes, where
document.getElementById would error out, $ returns some meaningful
result. Where document.getElementById would work, $ returns what
document.getElementById does return.
The dollar function calls Element.extend. Element.extend modifies the
element by adding a lot of properties to it.

I'm going to post up the code again, with my comments interspersed,
annotated GS:-

Object.extend(function(element) {
// (GS) if the element is null or has been extended, or is not an
ELEMENT_NODE, return
if (!element || element._extendedByPrototype ||
element.nodeType != 1 || element == window) return element;

// (GS) Copy the Methods (gets init'd below in refresh()
var methods = Object.clone(Methods),
tagName = element.tagName, property, value;

// extend methods for specific tags
if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);

// (GS) Copy the methods to the element
for (property in methods) {
value = methods[property];
if (Object.isFunction(value) && !(property in element))
element[property] = value.methodize();
}
element._extendedByPrototype = Prototype.emptyFunction;
return element;
}

-
Element.extend copies the methods to the element, calling isFunction()
and methodize().

The dollar function does not, in fact, return the same thing that
getElementById returns. The documentation explains this:
http://prototypejs.org/learn/extensions

Just the facts.
Jun 27 '08 #22
dhtml wrote:
On Jun 1, 4:27 am, RobG <rg...@iinet.net.auwrote:
>On Jun 1, 6:17 pm, VK <schools_r...@yahoo.comwrote:
[...]
>>If we are talking about $ function as implemented in Prototype.js then
it is document.getElementById with argument check added, so yes, where
document.getElementById would error out, $ returns some meaningful
result.
No, it doesn't. It unconditionally calls document.getElementById if
the argument is a string. There is no feature check or attempt at any
kind of error handling, either for the call or what it returns,
therefore where document.getElementById will error, so will
Prototype.js's $ function.

There's a check in Element.extend:
However, there is no check for document.getElementById().
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f8*******************@news.demon.co.uk>
Jun 27 '08 #23
VK
On Jun 2, 1:58 am, dhtml <dhtmlkitc...@gmail.comwrote:
The dollar function does not, in fact, return the same thing that
getElementById returns. The documentation explains this:http://prototypejs.org/learn/extensions

Just the facts.
This discussion was not so much about a particular function named $ in
Prototype.js library. It was overall about using $ identifier in
Javascript and in particular using $ identifier for a function being a
strict, lightweight or extended variant of Prototype.js one's: or even
just being a plain-vanilla wrapper over document.getElementById. Other
words, does $ identifier have any "by contract" semantic one should
account. Because even with Prototype.js in use no one is forcing to
use the default $ function. Just override it with a simple
function $(id) {
return document.getElementById(id) || null;
}
Jun 27 '08 #24
VK wrote:
[...] Because even with Prototype.js in use no one is forcing to
use the default $ function. Just override it with a simple
function $(id) {
return document.getElementById(id) || null;
}
I can imagine you would actually be capable of that kind of nonsense.
PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Jun 27 '08 #25
On Jun 1, 9:58 pm, VK <schools_r...@yahoo.comwrote:
On Jun 1, 3:27 pm, RobG <rg...@iinet.net.auwrote:
On Jun 1, 6:17 pm, VK <schools_r...@yahoo.comwrote:
[...]
If we are talking about $ function as implemented in Prototype.js then
it is document.getElementById with argument check added, so yes, where
document.getElementById would error out, $ returns some meaningful
result.
No, it doesn't. It unconditionally calls document.getElementById if
the argument is a string. There is no feature check or attempt at any
kind of error handling, either for the call or what it returns,
therefore where document.getElementById will error, so will
Prototype.js's $ function.

document.getElementById(nonExistingID) should not error out neither:
To reiterate what you posted:

"where document.getElementById would error out, $ returns
some meaningful result."

The Prototype.js $ function does not do anything of the sort.

it simply returns null (undefined?) so false in condition checks.
That is the specified behaviour, it has nothing to do with
Prototype.js handling cases where calling getElementById throws an
error.

Prototype's $ adds argument check for being an object reference.
No, it doesn't. It first checks the number of arguments and if there
is more than one, it calls itself recursively with each argument. If
there is one argument, it checks if it's a string and if so, calls
getElementById unconditionally. There is no error handling.

This
way where document.getElementById(objectReference) would search for id
"[object Object]" or "HTMLParagraphElement" or similar, $ simply
echoing the argument back.
No, it doesn't. If the argument is a string, it calls getElementById
and passes the result to Element.extend. Otherwise, it simply passes
the argument to Element.extend, whatever it is.
Such method polymorphism can be considered
as handy or bad as error-hiding but it would be all different question
then.
There is no error handling - zip, zero, nada, none.
--
Rob
Jun 27 '08 #26
On Jun 2, 7:40*am, dhtml <dhtmlkitc...@gmail.comwrote:
On Jun 1, 4:27*am, RobG <rg...@iinet.net.auwrote:
On Jun 1, 6:17*pm, VK <schools_r...@yahoo.comwrote:
[...]
If we are talking about $ function as implemented in Prototype.js then
it is document.getElementById with argument check added, so yes, where
document.getElementById would error out, $ returns some meaningful
result.
No, it doesn't. *It unconditionally calls document.getElementById if
the argument is a string. *There is no feature check or attempt at any
kind of error handling, either for the call or what it returns,
therefore where document.getElementById will error, so will
Prototype.js's $ function.

There's a check in Element.extend:

* var extend = Object.extend(function(element) {
* * if (!element || element._extendedByPrototype ||
* * * * element.nodeType != 1 || element == window) return element;

When the code reaches: if (!element
That is not error handling - if getElementById throws an error inside
the $ function, Element.extend won't even be called.

- it will return null, and element is null, then null (not undefined)
is returned.

Though it might have seemed more intuitive if the - if (!element) -
check had been done in the dollar function, prior to calling extend.
I don't have a problem with checking the returned value later
considering Element.extend is a "public" method, only the notion that
it is error handling. It just checks to see if the argument is
something it wants to add properties to (a sensible precaution),
otherwise it just returns it.
--
Rob
Jun 27 '08 #27
On Jun 1, 3:42*pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
dhtml wrote:
On Jun 1, 4:27 am, RobG <rg...@iinet.net.auwrote:
On Jun 1, 6:17 pm, VK <schools_r...@yahoo.comwrote:
[...]
However, there is no check for document.getElementById().
This:-

if(document.getElementById)

?

I guess that's what RobG was getting at, then.
PointedEars
Jun 27 '08 #28
On Jun 1, 3:52*pm, VK <schools_r...@yahoo.comwrote:
On Jun 2, 1:58 am, dhtml <dhtmlkitc...@gmail.comwrote:
The dollar function does not, in fact, return the same thing that
getElementById returns. The documentation explains this:http://prototypejs.org/learn/extensions
Just the facts.

This discussion was not so much about a particular function named $ in
Prototype.js library. It was overall about *using $ identifier in
Javascript and in particular using $ identifier for a function being a
strict, lightweight or extended variant of Prototype.js one's: or even
just being a plain-vanilla wrapper over document.getElementById. Other
words, does $ identifier have any "by contract" semantic one should
account. Because even with Prototype.js in use no one is forcing to
use the default $ function. Just override it with a simple
I brought the discussion this way because of the question: "What does
$ mean?" Language is just symbolism for thought and all words got made
up at some point. However, the new symbol needs an accurate
description. We don't go naming our variables arbitrary symbols, we
give them meaningful name. A way answer that question "What does $
mean," is to look to what the dollar function means to most
developers. When I see that dollar function, I think of PrototypeJS
from association and I assumed other developers might, too.

*function $(id) {
* return document.getElementById(id) || null;
*}
The null check is pointless; document.getElementById will return an
Element or null (if none found).

Jun 27 '08 #29
dhtml wrote:
On Jun 1, 3:42 pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
>dhtml wrote:
>>On Jun 1, 4:27 am, RobG <rg...@iinet.net.auwrote:
On Jun 1, 6:17 pm, VK <schools_r...@yahoo.comwrote:
[...]
However, there is no check for document.getElementById().
Maybe I should have said "There is no check for document.getElementById()
*there* (in Prototype.js's `$()').
This:-

if(document.getElementById)

?
This is only the first step in feature-testing a host object's method.
Search for isMethod() instead.
I guess that's what RobG was getting at, then.
Not quite.
PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
Jun 27 '08 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

29
by: Mark Hahn | last post by:
We are considering switching to the dollar sign ($) for self, instead of the period ( . ) we are using now in Prothon. Ruby uses the at-sign (@) for self, but our new usage of self also includes...
17
by: Digital Puer | last post by:
I've inherited some code where the coder placed dollar signs in his preprocessor macros. What is the significance of the dollar signs ($) ? Example: #define ALLOCATE(task,pointer) \ { \...
2
by: Yorian | last post by:
I just started to try regexps in php and I didn't have too many problems, however I found a few when trying to build a templte engine. The first one is found is the dollar sign. In my template I...
2
by: johnson4 | last post by:
Im wanting to display a dollar sign on my wap application, which requires that the cell phone is served with $$ to display $. Therefor I'm trying to find an easy way, in my php code, that will...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.