Reputation: 625
I am trying to access the elements of the document in the iframe from the parent document using the following code, but cannot get it to work for some reason.
Parent.html :
<!DOCTYPE html>
<html>
<head>
<title>Parent</title>
<script src='http://code.jquery.com/jquery-latest.min.js'>
</script>
</head>
<body>
<iframe id="iframe1" src="iframe.html">
</iframe>
<script type='text/javascript'>
$('#iframe1').ready(function()
{
console.log($('#iframe1').contents().find("#testDiv").html());
});
</script>
</body>
</html>
IFrame.html :
<!DOCTYPE html>
<html>
<head>
<title>Iframe</title>
</head>
<body>
<div id="testDiv">
Works!
</div>
</body>
</html>
All i am getting in console log is 'undefined' instead of 'Works!'. What am I doing wrong?
Thanks in advance.
Upvotes: 2
Views: 23328
Reputation: 97672
Try using load instead of ready.
$('#iframe1').load(function(){
console.log($('#iframe1').contents().find("#testDiv").html());
});
Upvotes: 9