I'm trying to access a particular element (maybe more similar to this) using iframe object and jQuery but it isn't working.
The iframeWindow
object is not null but the next statement doesn't seem working. I saw something like this on this answer but it doesn't work. Am I doing something wrong?
Here's my code:
RADIO.PHP
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
setTimeout(function(){
var iframe= document.getElementById("iframe");
var iframeWindow = iframe.contentWindow;
var text=iframeWindow.$("div:nth-child(3) .c2").html();
console.log(text);
//DOESN'T PRINT "INNER MOST"
}, 1000);
});
</script>
</head>
<body>
<div class="c1">
<iframe id="iframe" src="api.php" height="200" width="300">
</iframe>
</div>
</body>
</html>
API.PHP
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<script type="text/javascript" src="jquery.js"></script>
<body id="abody">
Hey
<div class="c1"></div>
<div class="c1">
<p class="c2"></p>
</div>
<div class="c1">
<p class="c2">
INNER MOST
</p>
</div>
</body>
</html>
EDIT: I've corrected syntax mistakes.
You should use iframe.contentWindow.document
instead of iframe.contentWindow
in combination with find()
and text()
and it should work. Try this:
$(document).ready(function() {
setTimeout(function() {
var iframe = document.getElementById("iframe");
var iframeWindow = iframe.contentWindow.document;
var text = $(iframeWindow).find(".c1:nth-child(3) .c2").text();
console.log(text);
//PRINTS "INNER MOST"
}, 1000);
});
As per MDN documentation says:
The contentWindow property returns the Window object of an iframe element. You can use this Window object to access the iframe's document and its internal DOM. This attribute is read-only, but its properties can be manipulated like the global Window object.
You can read more about iframe elements and how they work here.
That is something obvious to see the typo which i and all other missed, instead of inframeWindow
that should have to be iframeWindow
.
Instead try with jquery selector:
var text=$(iframeWindow).find("div:nth-child(3) .c2").html();
You are attaching a jquery method to a DOM object. which can't be done in that way. You have to make it a jQuery object to assign a jQuery method.
To specify a scope for a selector in jQuery, pass the scope as a second argument to the jQuery selector.
Replace:
inframeWindow.$("div:nth-child(3) p .c2")
with
$("div:nth-child(3) p .c2", inframeWindow)
(Also, there is no $
member function on DOM or jQuery objects.)
Try this way hope it will help
Updated Answer
var $iframe= $("#iframe");
var $iframeWindow = $iframe.contents();
var text=$iframeWindow.find("div").eq(2).find('p .c2').html();
console.log(text);