开发者

document.getElementById in IE

开发者 https://www.devze.com 2023-02-22 08:23 出处:网络
When I use document.getElementById in Internet Explorer I get this error: Mensaje: El objeto no acepta esta propiedad o método

When I use document.getElementById in Internet Explorer I get this error:

Mensaje: El objeto no acepta esta propiedad o método

Translation:

Object does not support this property or method

开发者_如何学运维

and the execution stops

Html:

  <div id="contenedor">
  ...
  </div>

JavaScript:

  contenedor = document.getElementById("contenedor");

This works ok in Firefox and Chrome.


There is a misfeature in some(?) versions of IE where it defines global constants for every id value in the document. So when you write contenedor = document.getElementById("contenedor") — notice that it uses the div's name for the variable — it sees you're trying to set that global variable and complains that you can't. What you should do is declare a new variable instead of setting a global: var contenedor = document.getElementById("contenedor")


If it's simply document.getElementById('someid') that gives you this message, may be placing your script at the bottom of the HMTL (right before the closing </body> tag) will help.

if you want to be shure the element is loaded before you assign it to a variable, use

window.onload = function(){
 contenedor = document.getElementById("contenedor");
};


It looks like your javascript is executing before DOM is ready. Many javascript libraries include a mechanism for adding an event when DOM is ready, otherwise, one can use the body onload event.

You can try to put your javascript at the bottom of your document, but this is no guarantee that the code won't be executed before the page has loaded sufficiently to allow the browser to build the DOM tree. You're much better off either using a framework with the ready or domready event (like mootools or jquery), OR using the body onload event as mentioned.

Example:

<html>
<head>
<script type="text/javascript">
  var initPage = function() {
    // do stuff
  }
</script>
</head>
<body onload="initPage();">
 <!-- page content -->
</body>
</html>
0

精彩评论

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