Email conversation
From | Gábor Kertész |
To | Me |
Subject | referencing elements by id |
Date | 12 June 2007 18:01 |
Dear Mark,
Suppose you have an element with a unique id, like
<div id="foo">...</div>
Why do you and many others keep referencing it using
document.getElementById("foo")
instead of just using the object foo? Are there situations or browsers this
will not work?
In some tutorials I see
var content = document.getElementById("content");
This seems pointless to me as before this assignment 'content' was already
the desired global object; in IE at least.
Thank you,
Gabor
From | Me |
To | Gábor Kertész |
Subject | Re: referencing elements by id |
Date | 12 June 2007 19:07 |
Gábor,
> Why do you and many others keep referencing it using
> document.getElementById("foo")
>
> instead of just using the object foo? Are there situations or browsers
> this will not work?
Because getElementById is in the DOM standard. Writing just the id is not in
any standard at all. There is nothing that requires a browser to create a
global variable for every element with an ID. IE does it anyway, some
browsers (Opera, Safari, Konqueror, iCab) do it to allow pages that are
designed only for IE to work. However, not all browsers implement this.
Firefox does not implement it if the page triggers standards rendering mode,
so if you just write the ID, it will fail on these pages.
In addition, other browsers may or may not implement the IE properties.
there is nothing that says they have to. Future versions of major browsers
may also drop support in future, since there is no requirement for them to
keep it.
Using getElementById works in all these browsers, always. No problems. It
will continue to work in these browsers, and future browsers, since it is
part of the DOM standard. That's why we use it.
> This seems pointless to me as before this assignment 'content' was already
> the desired global object; in IE at least.
Never rely on IE to be correct. It usually is not. It's standards support is
pathetically poor, and instead it implements non-standard properties like
this. If you are serious about Web development, stop trusting IE, and use
standards compliant browsers and Web standards, then add in the alternatives
needed to get IE support as needed. Trusting IE will only lead to Web sites
that break in other browsers.
Mark 'Tarquin' Wilton-Jones - author of http://www.howtocreate.co.uk/
From | Gábor Kertész |
To | Me |
Subject | Re: referencing elements by id |
Date | 12 June 2007 20:33 |
Mark,
Thanks a lot for clearing this up for me so fast.
Gabor