开发者

Javascript issue - intermittently cannot find element using getElementById

开发者 https://www.devze.com 2023-01-29 03:38 出处:网络
I am having a problem with some javascript that I wrote that is only working intermittently.I dont know a huge amount about how things work in the DOM but I suspect that the JS that I have written is

I am having a problem with some javascript that I wrote that is only working intermittently. I dont know a huge amount about how things work in the DOM but I suspect that the JS that I have written is trying to access an element in the DOM before it exists. I wrote the JS to add it to a formassembly form. I do not have access to the actual code in the form to make changes there, I can only make JS changes.

Here is the link to the form http://www.tfaforms.com/186347

and this is the javascript that I am using on document load

 window.onload=function() {

document.getElementById("submit-").style.visibility = "hidden";
document.getElementById("wfPageNextId1").value="Calculate";
document.getElementById('wfPageNextId1').setAttribute('onclick', 'Calculate2011()'开发者_如何学JAVA)

}

I am getting errors saying that wfPageNextId1 is null and setAttribute cannot be called.

Any help would be very much appreciated. Thanks in advance.


It looks like some of the DOM is getting created dynamically by other scripts. You can delay until the elements exist via something along these lines:

function initializeForm() {
   var submit = document.getElementById("submit-"),
       nextPage = document.getElementById("wfPageNextId1");
   if (submit && nextPage) {
      submit.style.visibility = "hidden";
      nextPage.value = "Calculate";
      nextPage.setAttribute('onclick', 'Calculate2011()');
   } else {
      // try again in 1 second
      setTimeout(initializeForm, 1000);
   }
}

window.onload = function() {
   initializeForm();
};

You should also make sure you are not nuking any window.onload defined in the other scripts:

if (window.onload) {
   var currentOnload = window.onload;
   window.onload = function() { currentOnload(); initializeForm(); };
} else {
   window.onload = function() { initializeForm(); };
}


Checked the page HTML and infact there is no HTML element with the id wfPageNextId1. What is the element on the page that you are trying to access?

0

精彩评论

暂无评论...
验证码 换一张
取 消