"Uncaught TypeError: content.getElementById is not a function"

Viewed 2145

I already tried a lot but every time i get this error: "Uncaught TypeError: content.getElementById is not a function" (Script attached)

Help would be very much appreciated :D took me hours and couldnt figure out

var newcode = "";
var oldcode = "";

function update(){
 var iframe = document.getElementById('if');
 var content = iframe.contentWindow.document.getElementsByTagName('html')[0].getElementsByTagName('body')[0];
 newcode = content.getElementById("code").innerHTML;
 
 
 
 if(newcode != oldcode){
  oldcode = newcode;
  alert("lol"+newcode+"lol");
  document.head.innerHTML += "<script>"+newcode;
 }
 
}

window.setInterval(function(){
 update();
}, 5000);
<html>
<head>
<title>Check</title>
</head>
<body>
<iframe id="if" src="myurl"></iframe>
</body>
</html>

1 Answers

getElementById is only callable on a document - it isn't callable on an HTMLElement (not even on an HTMLBodyElement). IDs are supposed to be unique in a document, after all. Change to

var newCode = iframe.contentWindow.document.getElementById('code').innerHTML;

so that iframe.contentWindow.document refers to the document inside the iframe.

If you want to select only a particular ID from an ancestor node without going back to the document, it's possible to do so with querySelector - just prefix the ID with #:

var newcode = content.querySelector("#code").innerHTML;

(but there's no need to navigate to the content in the first place, here, assuming the HTML is valid)

Related