473,727 Members | 2,009 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Replacing document.getEle mentById with $ (dollar sign)

I've seen a few frameworks use the following:

function $(id) { return document.getEle mentById(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 19277
On May 28, 8:47 am, Nick <nick.lemou...@ gmail.comwrote:
I've seen a few frameworks use the following:

function $(id) { return document.getEle mentById(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.getEle mentById 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.ne t.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.getEle mentById(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.getEle mentById(id); }

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

document.getEle mentById("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...@g mail.comwrote:
On May 27, 4:32 pm, RobG <rg...@iinet.ne t.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.getEle mentById(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.getEle mentById(id); }
To do as specified above, it needs something like:

function $(id) {
return (typeof id == 'string')? document.getEle mentById(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.getEle mentById("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...@g mail.comwrote:
On May 27, 4:32 pm, RobG <rg...@iinet.ne t.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.getEle mentById(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.getEle mentById(id); }

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

document.getEle mentById("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...@g mail.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.getEl ementById" 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...@gma il.comwrote:
On May 27, 6:07 pm, dhtml <dhtmlkitc...@g mail.comwrote:
On May 27, 4:32 pm, RobG <rg...@iinet.ne t.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.getEle mentById(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.getEle mentById(id); }
$("aDiv") results in two function calls, but:-
document.getEle mentById("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.getElementByI d("x"),
y = d.getElementByI d("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.leng th 1) {
for (var i = 0, elements = [], length = arguments.lengt h; i <
length; i++)
elements.push($ (arguments[i]));
return elements;
}
if (Object.isStrin g(element))
element = document.getEle mentById(elemen t);
return Element.extend( element);
}

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

$.............. ............... .+1
+--document.getEle mentById....+1
+--Element.extend. ............+1

3 calls so far. Looking at Object.extend:

Object.extend(f unction(element ) {
if (!element || element._extend edByPrototype ||
element.nodeTyp e != 1 || element == window) return element;

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

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

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

element._extend edByPrototype = Prototype.empty Function;
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.getEle mentById with $"

var $ = document.getEle mentById;
$("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.getEle mentById with $"

var $ = document.getEle mentById;
$("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.n ame);
}

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_B AD_OP_ON_WN_PRO TO", 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 bugRiddenCrashP ronePieceOfJunk = (
navigator.userA gent.indexOf('M SIE 5') != -1
&& navigator.userA gent.indexOf('M ac') != -1
) // Plone, register_functi on.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.getEl ementById" 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 ".getElementByI d" 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.getEl ementById" 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

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

Similar topics

29
22183
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 replacing the period for some attribute references, as in obj$func() versus obj.func(), and too many programs treat that as an email address and screw it up. Also the S in the symbol $ reminds one of the S in $elf. Can people from outside the...
17
10336
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) \ { \ long task$; \ if (task == FOO) { \ task$ = ZERO); \
2
3041
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 would like to write this: {$var} where var ofcourse will be replaced by the real var however I'm having trouble with the dollar sign I do escape the it though, my regexp:
2
2319
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 always add a dollar sign next to any existing dollar sign. so that dollar signs are always served in pairs The content is residing in a MySQL database. Thanks for any help that can be offered.
0
8891
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9406
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9260
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9185
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4521
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4786
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.