Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Document.Head is Null

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>
like image 598
qweqweqwe Avatar asked Jul 29 '13 18:07

qweqweqwe


People also ask

Why is document body null?

body object, it is most likely because the body has not been defined yet. If document. body is null, you most likely need to execute your code in the window. onload function.

What is document head Javascript?

<head>: The Document Metadata (Header) element The <head> HTML element contains machine-readable information (metadata) about the document, like its title, scripts, and style sheets.

What is the document head?

The HEAD element contains header information about the document, such as its title, keywords, description, and style sheet. HEAD is required in all documents, but its start and end tags are always optional.

What is inserting elements into document head?

The content to be added can be first created using the createElement() method and the required properties can be assigned to it. The appendChild() method appends this created element to the head of the document.


1 Answers

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
like image 76
Ian Avatar answered Oct 03 '22 06:10

Ian