Welcome to WebmasterWorld Guest from 54.145.209.34

Forum Moderators: open

Test for assignment fails in IE

Any particular reason?

   
5:18 pm on Mar 16, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This is more out of interest than a real issue as I can easily work around it, but given the following snippet of code:

if (my_var = document.getElementById("my_element")) {...do something...}

In Firefox this works; in IE it doesn't. I'd assume this works in Fx because if the DOM call fails my_var is undefined and the if() test fails, but I'm probably barking up the wrong tree :) Ideas why this isn't working in IE? It'd be nice if it did because it saves a second DOM call immediately afterwards (assuming browsers don't cache that sort of thing).

11:11 pm on Mar 17, 2007 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



I don't quite understand what you mean when you say it doesn't work ...? I'm running a simple test in both Fx and IE6 and they both work fine, as long as the object has been defined in the document first.
<input name="my_element" id="my_element"> 
<script type="text/javascript">
if (my_var = document.getElementById("my_element")) {
alert('yep, my_var exists: ' + typeof my_var)
} else {
alert('nope, my_var does not exist: ' + typeof my_var)
}
</script>
6:10 am on Mar 18, 2007 (gmt 0)

10+ Year Member



Seems strange to me too. I'd guess that IE has even more chanses to return true because ie returns true even in the case when the "name" attribute is "my_element" and id is "his_element" due to coder mistake, for example.
8:40 pm on Mar 18, 2007 (gmt 0)

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



I agree with coopster... FF1.5, IE6 and Opera8 ('all browsers') all behave the same in the 'test for assignment' as far as I can tell. The reverse test...

if (my_var = document.getElementById("element_does_not_exist")) {  
alert('[1] yep, it exists!')
} else {
alert('[2] nope, it does not exist (expected result)')
}

Produces the [2] alert in all browsers (as expected).

I'd assume this works in Fx because if the DOM call fails my_var is undefined and the if() test fails

document.getElementById("element_does_not_exist")
returns null (as opposed to undefined) in all browsers.

I can only think that the reason why your test fails in IE is to do with where it is being called (before onload?) and maybe the order in which IE builds the page...?

9:55 am on Mar 19, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks for the answers, all interesting :) For what it's worth it turned out to be a variable initialisation issue. Adding
var my_var;
before the if() test made this work in IE.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month