473,881 Members | 1,572 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
29 19325
dhtml <dh**********@g mail.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...@g mail.comwrote:
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:

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.
<clarificatio n>
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.javas cript message <b7a3a120-34f7-48e3-8668-2c51b052f0d4@h1
g2000prh.google groups.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.getEle mentById(id); }

Then to use:

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

function Wryt(ID, S) { document.getEle mentById(ID).in nerHTML = 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.demo n.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...@g mail.comwrote:
On May 28, 10:05 am, dhtml <dhtmlkitc...@g mail.comwrote:
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:
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.

<clarificatio n>
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.getEle mentById 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.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.

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 "mechanical ly generated code" in
application to Javascript. In Java where the sentence in question is
coming from it referred to $SubClass1.clas s, $SubClass2.clas s etc.
separate package files automatically generated by javac for dependent
classes of the main class. What is "mechanical ly 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
"mechanical ly 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.getEle mentById 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.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.
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...@y ahoo.comwrote:
On May 30, 5:06 am, dhtml <dhtmlkitc...@g mail.comwrote:
On May 28, 10:05 am, dhtml <dhtmlkitc...@g mail.comwrote:
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:
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.
<clarificatio n>
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.getEle mentById 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
HTMLTableRowEle ment, or someNode.__prot o__ 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.getEle mentById 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...@g mail.comwrote:
On May 31, 5:27 am, VK <schools_r...@y ahoo.comwrote:
On May 30, 5:06 am, dhtml <dhtmlkitc...@g mail.comwrote:
On May 28, 10:05 am, dhtml <dhtmlkitc...@g mail.comwrote:
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:
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.
<clarificatio n>
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.getEle mentById 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.protot ype
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
HTMLTableRowEle ment, or someNode.__prot o__ 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.getEle mentById would
return.
If we are talking about $ function as implemented in Prototype.js then
it is document.getEle mentById with argument check added, so yes, where
document.getEle mentById would error out, $ returns some meaningful
result. Where document.getEle mentById would work, $ returns what
document.getEle mentById does return.
Jun 27 '08 #17
On Jun 1, 6:17*pm, VK <schools_r...@y ahoo.comwrote:
[...]
If we are talking about $ function as implemented in Prototype.js then
it is document.getEle mentById with argument check added, so yes, where
document.getEle mentById would error out, $ returns some meaningful
result.
No, it doesn't. It unconditionally calls document.getEle mentById 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.getEle mentById will error, so will
Prototype.js's $ function.
--
Rob
Jun 27 '08 #18
VK
On Jun 1, 3:27 pm, RobG <rg...@iinet.ne t.auwrote:
On Jun 1, 6:17 pm, VK <schools_r...@y ahoo.comwrote:
[...]
If we are talking about $ function as implemented in Prototype.js then
it is document.getEle mentById with argument check added, so yes, where
document.getEle mentById would error out, $ returns some meaningful
result.

No, it doesn't. It unconditionally calls document.getEle mentById 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.getEle mentById will error, so will
Prototype.js's $ function.
document.getEle mentById(nonExi stingID) 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.getEle mentById(object Reference) would search for id
"[object Object]" or "HTMLParagraphE lement" 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.ne t.auwrote:
>On Jun 1, 6:17 pm, VK <schools_r...@y ahoo.comwrote:
[...]
>>If we are talking about $ function as implemented in Prototype.js then
it is document.getEle mentById with argument check added, so yes, where
document.getE lementById would error out, $ returns some meaningful
result.
No, it doesn't. It unconditionally calls document.getEle mentById 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.getEle mentById will error, so will
Prototype.js 's $ function.

document.getEle mentById(nonExi stingID) should not error out neither:
But it could.
it simply returns null (undefined?)
If it can be called.
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 #20

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

Similar topics

29
22221
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
10460
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
3050
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
2327
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
9776
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
11096
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
10716
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
10812
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
10400
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7108
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();...
1
4597
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
2
4194
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.