Forum Moderators: open
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).
<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>
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...?