getElementById in Firefox iframe returns null but works in Safari/Chrome
-
23-09-2019 - |
Question
I've two html files. One includes the other in an iframe. The iframe executes a getElementById on a previously created element. This works fine in Chrome/Safari but doesn't in Firefox/IE8, and I don't understand why.
Firefox returns: null
Safari returns: [object HTMLDivElement]
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>untitled</title>
</head>
<body>
<iframe src="comment.html"></iframe>
</body>
</html>
comment.html
<div id="foobar"></div>
<script type="text/javascript">
alert(document.getElementById('foobar'));
</script>
Solution
Your comment html file is not properly formed. Try using:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>untitled</title>
</head>
<body>
<div id="foobar"></div>
<script type="text/javascript">
alert(document.getElementById('foobar'));
</script>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow