tags:

views:

328

answers:

4

Hi,

I am modifying existing legacy webpages(which i shouldn't modify existing parts but adding) and the webpage uses document.write to write certain html elements. when i use

<script type="text/javascript" language="javascript">
   var  v = document.getElementById('td_date_cal_0');
   alert(v);
</script>

v becomes null and when i create button and click

<input type="button" id="mnbutton" onclick="mnLoader();" value="Click Me!" />;
<script type="text/javascript" language="javascript" >
    function mnLoader() {
        var v = document.getElementById("td_date_cal_0");
        alert(v); 
    } <br />

</script>

Any idea, how to get the element without need of user action, such as clicking?

Thanks, Ebe

+1  A: 

I'm guessing you are placing your script element before the element you are trying to get.

The simplest way to resolve this is to put your script element immediately before the END tag for the body element.

David Dorward
+8  A: 

Try attaching the script to the onload event of either document or window.

function mnLoader() {
 var v = document.getElementById("td_date_cal_0");
 alert(v); 
}
// Execute the function after the page has loaded
document.onload = function() {
 mnLoader();
}
Mathias Bynens
Mathias is right. The problem you are experiencing is due to the fact that the DOM element you are trying to get hasn't been actually added to the DOM, in memory yet.. the window.onload is a solution but there are others too..
Miky Dinescu
Also document.write is toxic, use DOM methods or innerHTML if you must
annakata
+1  A: 

I expect this is happening because at the point the script runs before the element with ID "td_date_cal_0" has been created.

Try moving the script to beneath the element that it is manipulating or wire the code up to the document.onload event.

d4nt
A: 

@Mathias gave an example that will most likely fix your problem. Which is that the element you're trying to access using document.getElementById hasn't been loaded into the DOM yet at the time you're trying it.

However, if you're interested in being able to run your code as early as possible a better solution is to observer the "dom:loaded" event, or DOM ready event. This is a bit more involved than calling window.onload but a framework such as Prototype.js or jQuery can help.

See this page in which Michael Sharman talks about just this very feature.

You can then write code such as:


document.observe(document, 'dom:loaded', initFunction);   

function initFunction()  
{  
  // this code will run as soon as DOM is loaded, 
  // but before any images are loaded
}

Obviously if you don't want to use a framework, you can replicate the behavior using just the standard javascript calls but you will have to be prepared to deal with differences between browsers. You can start by looking at the onreadystatechanged event and the similar events for other browsers (i.e. DOMContentLoaded)

Miky Dinescu