Get element using id problem
I am modifying existing legacy web pages (which I am not supposed to modify the existing parts other than adding) and the web page uses document.write to write specific 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 a 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 item without the need for user action like clicking?
Thanks, Ebe
@Mathias gave an example that will most likely fix your problem. This is that the element you are trying to get with document.getElementById has not yet been loaded into the DOM at the time you are trying it.
However, if you are interested in being able to run your code as early as possible, the best solution is to look at the dom: loaded event or DOM event . This is a little more than calling window.onload, but a structure like Prototype.js or jQuery can help.
See this page in which Michael Sharman talks about this very feature.
Then you can write some code like:
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 only standard javascript calls, but you must be prepared for the difference between browsers. You can start by looking at the onreadystatechanged event and similar events for other browsers (i.e. DOMContentLoaded )
a source to share