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

0


a source to share


5 answers


Try to connect the script to the event onload

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();
}

      

+8


a source


I am assuming that you are placing your script element in front of the element you are trying to get.



The easiest way to resolve this is to add a script element just before the END tag for the body element.

+1


a source


I expect this to happen because at the point the script is executed before the element with id "td_date_cal_0" was created.

Try to move your script under the element it controls, or wire your code to the document.onload event.

+1


a source


@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 )

0


a source


the following code works correctly.

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

      

0


a source







All Articles