473,595 Members | 2,646 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why doesn't window.document .getElementById ('junk') return 'undefined'?

.... when the id 'junk' doesn't exist anywhere in the document,
instead of returning 'object'?!

I am using Javascript for a drop-down menu, slightly adapted from
one by Angus Turnbull (see http://javascript.internet.com and
http://gusnz.cjb.net, not that this is probably relevant but
it deserves a plug ;-), on Internet Explorer v6.0.2800.1106.

I need this feature of getElementById( ), or an equivalent one
(using sound and standard Javascript), in order to know if an
HTML element is defined in the document, and this bug/feature
is driving me nuts: Whatever string I supply to getElementById( )
the result is always 'object' whether the string exists or not
as an ID.
Cheers

John Ramsden (jo**********@s agitta-ps.com)
Jul 20 '05 #1
6 46555


John Ramsden wrote:
... when the id 'junk' doesn't exist anywhere in the document,
instead of returning 'object'?!

I am using Javascript for a drop-down menu, slightly adapted from
one by Angus Turnbull (see http://javascript.internet.com and
http://gusnz.cjb.net, not that this is probably relevant but
it deserves a plug ;-), on Internet Explorer v6.0.2800.1106.

I need this feature of getElementById( ), or an equivalent one
(using sound and standard Javascript), in order to know if an
HTML element is defined in the document, and this bug/feature
is driving me nuts: Whatever string I supply to getElementById( )
the result is always 'object' whether the string exists or not
as an ID.


document.getEle mentById returns null if an element of the id passed is
not found, you can for instance script
var element = document.getEle mentById('whate ver');
if (element) {
... // use element
}

--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #2
Martin Honnen <Ma***********@ t-online.de> wrote in message news:<3f******* *@olaf.komtel.n et>...
John Ramsden wrote:
... when the id 'junk' doesn't exist anywhere in the document,
instead of returning 'object'?!

[...]

I need this feature of getElementById( ), or an equivalent one
(using sound and standard Javascript), in order to know if an
HTML element is defined in the document, and this bug/feature
is driving me nuts: Whatever string I supply to getElementById( )
the result is always 'object' whether the string exists or not
as an ID.


document.getEle mentById returns null if an element of the id passed is
not found, you can for instance script
var element = document.getEle mentById('whate ver');
if (element) {
... // use element
}


Thanks for the reply Martin. I have seen the method you suggest used
in other Javascript examples. But a couple of references I've come
across on-line claim it isn't really kosher, as several values such
as 0 or '' etc all evaluate to false.

I'd really prefer to do things by the book if possible, especially
being a Javascript novice, and these references definitely say one
is supposed to use typeof() for object existence checking.

But then if IE isn't doing things by the book, and is returning a
value it shouldn't, I guess that means some other approach, such
as "if (element)", must be used.

BTW, I'm not the only person to have this problem. See:

http://forums.devshed.com/archive/1/2002/08/1/40857
Cheers

John Ramsden (jo**********@s agitta-ps.com)
Jul 20 '05 #3


John Ramsden wrote:
Martin Honnen <Ma***********@ t-online.de> wrote in message news:<3f******* *@olaf.komtel.n et>...
John Ramsden wrote:

... when the id 'junk' doesn't exist anywhere in the document,
instead of returning 'object'?!

[...]

I need this feature of getElementById( ), or an equivalent one
(using sound and standard Javascript), in order to know if an
HTML element is defined in the document, and this bug/feature
is driving me nuts: Whatever string I supply to getElementById( )
the result is always 'object' whether the string exists or not
as an ID.


document.getE lementById returns null if an element of the id passed is
not found, you can for instance script
var element = document.getEle mentById('whate ver');
if (element) {
... // use element
}

Thanks for the reply Martin. I have seen the method you suggest used
in other Javascript examples. But a couple of references I've come
across on-line claim it isn't really kosher, as several values such
as 0 or '' etc all evaluate to false.

I'd really prefer to do things by the book if possible, especially
being a Javascript novice, and these references definitely say one
is supposed to use typeof() for object existence checking.

But then if IE isn't doing things by the book, and is returning a
value it shouldn't, I guess that means some other approach, such
as "if (element)", must be used.


typeof null yields "undefined" therefore a check with typeof doesn't
help to decide whether document.getEle mentById has returned null or a
non null reference to an object.

--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #4
"John Ramsden" <jo**********@s agitta-ps.com> wrote in message
news:d2******** *************** **@posting.goog le.com...
Martin Honnen <Ma***********@ t-online.de> wrote in message news:<3f******* *@olaf.komtel.n et>...
<snip>
document.getE lementById returns null if an element of the
id passed is not found, you can for instance script
var element = document.getEle mentById('whate ver');
if (element) {
... // use element
}


Thanks for the reply Martin. I have seen the method you
suggest used in other Javascript examples. But a couple of
references I've come across on-line claim it isn't really
kosher, as several values such as 0 or '' etc all evaluate to
false.


Martin's test is completely valid and sensible. The rules that apply to
automatic type conversion to boolean are ECMA 262 specified and
consistently implemented (as long as you avoid ever specifying a
language version of 1.2). And a type-conversion to boolean will always
return a true value for an object reference and a false value for null.
As you need to discriminate null from an object reference it is the
ideal test to apply.
I'd really prefer to do things by the book if possible,
especially being a Javascript novice, and these references
definitely say one is supposed to use typeof() for object
existence checking.
Both object references and null return the string "object" from the
typeof operator (parenthesise are not necessary (and can be confusing)
when using typeof as it is not a function but on operator). Therefore
typof tests are not appropriate to this situation.

In programming ("by the book" or otherwise) the test to use is the one
that tells you what you need to know.
But then if IE isn't doing things by the book,
and is returning a value it shouldn't,
The book in question in this case is the W3C DOM core specification and
in this case IE is doing exactly what it should and returning null if it
cannot find an element with the provided ID.
I guess that means some other
approach, such as "if (element)", must be used.

<snip>

Yes, the correct approach for the situation is the one to use.

Richard.
Jul 20 '05 #5
Martin Honnen <Ma***********@ t-online.de> writes:
in other Javascript examples. But a couple of references I've come
across on-line claim it isn't really kosher, as several values such
as 0 or '' etc all evaluate to false.
They do. The values that are "falsy" (converts to false in a boolean
context) are:
false, 0, NaN, null, undefined, ""
No object (including arrays) will convert to false. In this case,
the return value of document.getEle mentById is either null (false)
or a DOM node (an object, i.e., true).
being a Javascript novice, and these references definitely say one
is supposed to use typeof() for object existence checking.
Exactly for objects, it is *not* necessary.

When checking for the existence of object properties, you should
compare with strict equality check ("===") to undefined.

if (obj.property === undefined) { ... // doesn't exist }
or
if (obj.property !== undefined) { ... // exists }

(Some older browsers don't have "undefined" as a global variable. If
coding for these, either use
typeof obj.property != "undefined"
or add this earlier in the code:
window.undefine d = window.undefine d;
But then if IE isn't doing things by the book, and is returning a
value it shouldn't, I guess that means some other approach, such
as "if (element)", must be used.

My IE6 returns "null" if the element isn't there.
typeof null yields "undefined"
(You mean "object")
therefore a check with typeof doesn't
help to decide whether document.getEle mentById has returned null or a
non null reference to an object.


Exactly.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #6
Many thanks for the replies everyone. That's definitely settled it,
and my code is now working fine.
Cheers

John Ramsden (jo**********@s agitta-ps.com)
Jul 20 '05 #7

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

Similar topics

4
1821
by: Zhang Weiwu | last post by:
This is really very stange. I have a form like this: <form id="form_A"> xxxx </form> This form is on one page in a page of a web application, it is the only form on that page. on the end of the page in javascript: document.getElementById("form_A").submit(); In the begining it works very well, after I restarted the browser and did some small modification (I don't recall, but far from chaning that
3
9254
by: davidkarlsson74 | last post by:
Error: document.getElementById("folderMenu").cells has no properties File: http://www.volkswagen.se/tillbehor/js/foldermenu.js Rad: 49 The function activates different DIV:s, but doesn't seem to work on FireFox or Netscape. What could be wrong? The function: function setActiveTab(tabNo) {
20
6947
by: weston | last post by:
I've got a piece of code where, for all the world, it looks like this fails in IE 6: hometab = document.getElementById('hometab'); but this succeeds: hometabemt = document.getElementById('hometab'); Has anyone ever seen anything like this before, or am I dreaming?
6
4030
by: Billy | last post by:
I have a ReportViewer control (from reporting service) in one asp.net web page. The document.getElementById("ReportViewerID") always returns a null. Other controls in the pages seems OK and the function can return the right object. Could anyone help me out? Thanks,
5
1984
by: RC | last post by:
Please look at this page: http://www.norbertverboeket.com/test There are 2 stylesheets, StyleSheet.css and BigStyle.css. One is copied from the other. Only the font-size is changed, so there couldn't be anything wrong with the copy. When the user clicks on 'Click here', the function SwitchSheets should switch the stylesheets: document.all.SetAttribute("HREF", "BigStyle.css",0);
2
1795
by: nyluke | last post by:
If I embed a movie (Quicktime or anything) in a DIV and then use javascript to change the innerHTML of that DIV, the movie keeps playing invisibly (I can hear the audio) after the change. This works in every browser except Safari. Anyone know a fix? Tx
4
12747
by: Claudio Calboni | last post by:
Hello folks, I'm having some performance issues with the client-side part of my application. Basically, it renders a huge HTML table (about 20'000 cells in my testing scenario), without content. Content is "pushed" from the back via some JS, for the only displayed portion of table. Once the user scrolls, JS updates visible cells with data. It's quite the philosophy behind GMaps and similars. So, the server says to JS "update this group...
2
2264
by: vps | last post by:
Please help me get the value of a textarea field: --------------------- The script --------------------- <html> <head> <script type="text/javascript">
29
19204
by: Nick | last post by:
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
0
8260
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
8379
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
8017
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
8250
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
5416
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
3872
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...
1
2391
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
1
1490
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1222
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.