最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - JavaScript Document.Head is Null - Stack Overflow

programmeradmin1浏览0评论

Getting an error when running the following code in IE 8, but not in other browsers:

'document.head' is null or not an object

Here is my code:

  <!DOCTYPE html>
   <html>
   <head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
   <link rel="stylesheet" type="text/css" href="style.css" media="screen" />
   <script type="text/javascript" src="respond.min.js"></script>

    <script>
   function load() {
    document.getElementsByID("myFrame");
    }
   </script>
   </head> 
   <body>       

    <iframe src="/" width="300" height="400" frameborder="0" scrolling="no" allowtransparency="true" id="myFrame" onload="load()"></iframe>

</body>
</html>

Getting an error when running the following code in IE 8, but not in other browsers:

'document.head' is null or not an object

Here is my code:

  <!DOCTYPE html>
   <html>
   <head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
   <link rel="stylesheet" type="text/css" href="style.css" media="screen" />
   <script type="text/javascript" src="respond.min.js"></script>

    <script>
   function load() {
    document.getElementsByID("myFrame");
    }
   </script>
   </head> 
   <body>       

    <iframe src="http://instagram.com/p/bTlK6CRNcL/embed/" width="300" height="400" frameborder="0" scrolling="no" allowtransparency="true" id="myFrame" onload="load()"></iframe>

</body>
</html>
Share Improve this question edited Jul 29, 2013 at 18:39 qweqweqwe asked Jul 29, 2013 at 18:32 qweqweqweqweqweqwe 3435 gold badges8 silver badges19 bronze badges 1
  • Framework I'm using for compatibility across browsers. – qweqweqwe Commented Jul 29, 2013 at 18:38
Add a comment  | 

1 Answer 1

Reset to default 18

document.head fails because IE8 doesn't support it (no version of IE before 9); it's a new feature of HTML5. Instead, you could use the following in any browser:

var head = document.head || document.getElementsByTagName("head")[0];

If document.head is defined (available), it will short-circuit and use that immediately. If it's not defined, it will use the document.getElementsByTagName part, which will find it in any browser.

Unless you want to have this kind of this || that throughout your code, it's safe and good enough to just always use document.getElementsByTagName("head")[0].


References:

  • document.head - https://developer.mozilla.org/en-US/docs/Web/API/document.head (scroll to the bottom for browser support)
  • document.getElementsByTagName - https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByTagName
发布评论

评论列表(0)

  1. 暂无评论