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>
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.
<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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With