Why can't I traverse this element using iframe object and jQuery? - javascript

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.

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.)

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.

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);

Related

How to put HTML inside of a jquery or javascript function to to be appended later?

Sorry there might be an answer somewhere out there, but I was having trouble finding it as well as trying to do it myself. But I was wondering if I could get an example of putting HTML inside of a jQuery function as well as a javascript function so that I can use it later to append to DOMs.
HTML
<div class="container>
</div>
jQuery
$(function (nothing){
'<h3>Nothing Here</h3>'
});
$(".container").append(function(nothing));
RESULT
Nothing Here
I am an even bigger noob with javascript, but I'd like to achieve the same result. Can someone show me how? Also, is there a difference in using the javascript method VS the jQuery method? thanks!
Javascript answer:
domElement.innerHTML is the API to add any html content inside the domElement.
And the html content can be returned from the javascript function in string format.
<!DOCTYPE html>
<html>
<body>
<div id="container">
</div>
<script> function getHTMLContent() {
return "<h2>Nothing here</h2>";
}</script>
<script>
document.getElementById("container").innerHTML = getHTMLContent();
</script>
</body>
</html>
Jquery answer: Instead of .innerHTML we have .append in jquery. This also takes string as parameter. And there is no difference in the way we call the javascript function.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function getHTMLContent() {
return "<h2>Nothing here</h2>";
}
$("#container").append(getHTMLContent());
});
</script>
</head>
<body>
<div id="container">
</div>
</body>
</html>
And regarding your doubt on function() and $function()..
$(function() { ... });
is just jQuery short-hand for
$(document).ready(function() { ... });
It gets called automatically once the page is ready.
But in javascript when you declare function(), this is not called by itself. You have to explicitly call it.
function nothing(){
$(".container").append('nothing');
}

document.getElementsByTagName returning undefined on placing the script after body

I know that this is a frequently asked question.
I have tried all the methods like using onload() for body tag,
placing the script after the DOM elements and using self invoking function.
Yet I get that my element is undefined.
P.S: document.getElementsByTagName('') replaced with document.getElementById('') works fine. Why is that? Please explain both of my doubts. Here is my simple code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="loadHandler()">
<p>Drag me!</p>
<script type="text/javascript">
function loadHandler() {
document.getElementsByTagName('p').setAttribute('draggable', true);
}
</script>
</body>
</html>
getElementsByTagName (as the name suggests) returns an array of elements. If you want the first one, take the first one.
.highlight{ color: red}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="loadHandler()">
<p>Drag me!</p>
<script type="text/javascript">
function loadHandler() {
var elem = document.getElementsByTagName('p')[0];
elem.setAttribute('draggable',true)
elem.classList.add('highlight');
}
</script>
</body>
</html>
As for why dragging is not working, perhaps the documentation might shed some light
By default, only text selections, images, and links can be dragged. For all others elements, the event ondragstart must be set for the drag and drop mechanism to work, as shown in this comprehensive example.
getElementsByTagName returns array of results, not just a single result like getElementById. Try to use getElementsByTagName('p')[0].

Nested iframes, AKA Iframe Inception

Using jQuery I am trying to access div id="element".
<body>
<iframe id="uploads">
<iframe>
<div id="element">...</div>
</iframe>
</iframe>
</body>
All iframes are on the same domain with no www / non-www issues.
I have successfully selected elements within the first iframe but not the second nested iframe.
I have tried a few things, this is the most recent (and a pretty desperate attempt).
var iframe = jQuery('#upload').contents();
var iframeInner = jQuery(iframe).find('iframe').contents();
var iframeContent = jQuery(iframeInner).contents().find('#element');
// iframeContent is null
Edit:
To rule out a timing issue I used a click event and waited a while.
jQuery().click(function(){
var iframe = jQuery('#upload').contents().find('iframe');
console.log(iframe.find('#element')); // [] null
});
Any ideas?
Thanks.
Update:
I can select the second iframe like so...
var iframe = jQuery('#upload').contents().find('iframe');
The problem now seems to be that the src is empty as the iframe is generated with javascript.
So the iframe is selected but the content length is 0.
Thing is, the code you provided won't work because the <iframe> element has to have a "src" property, like:
<iframe id="uploads" src="http://domain/page.html"></iframe>
It's ok to use .contents() to get the content:
$('#uploads).contents() will give you access to the second iframe, but if that iframe is "INSIDE" the http://domain/page.html document the #uploads iframe loaded.
To test I'm right about this, I created 3 html files named main.html, iframe.html and noframe.html and then selected the div#element just fine with:
$('#uploads').contents().find('iframe').contents().find('#element');
There WILL be a delay in which the element will not be available since you need to wait for the iframe to load the resource. Also, all iframes have to be on the same domain.
Hope this helps ...
Here goes the html for the 3 files I used (replace the "src" attributes with your domain and url):
main.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>main.html example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function () {
console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // nothing at first
setTimeout( function () {
console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // wait and you'll have it
}, 2000 );
});
</script>
</head>
<body>
<iframe id="uploads" src="http://192.168.1.70/test/iframe.html"></iframe>
</body>
iframe.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>iframe.html example</title>
</head>
<body>
<iframe src="http://192.168.1.70/test/noframe.html"></iframe>
</body>
noframe.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>noframe.html example</title>
</head>
<body>
<div id="element">some content</div>
</body>
var iframeInner = jQuery(iframe).find('iframe').contents();
var iframeContent = jQuery(iframeInner).contents().find('#element');
iframeInner contains elements from
<div id="element">other markup goes here</div>
and iframeContent will find for elements which are inside of
<div id="element">other markup goes here</div>
(find doesn't search on current element) that's why it is returning null.
Hey I got something that seems to be doing what you want a do. It involves some dirty copying but works. You can find the working code here
So here is the main html file :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
Iframe = $('#frame1');
Iframe.on('load', function(){
IframeInner = Iframe.contents().find('iframe');
IframeInnerClone = IframeInner.clone();
IframeInnerClone.insertAfter($('#insertIframeAfter')).css({display:'none'});
IframeInnerClone.on('load', function(){
IframeContents = IframeInner.contents();
YourNestedEl = IframeContents.find('div');
$('<div>Yeepi! I can even insert stuff!</div>').insertAfter(YourNestedEl)
});
});
});
</script>
</head>
<body>
<div id="insertIframeAfter">Hello!!!!</div>
<iframe id="frame1" src="Test_Iframe.html">
</iframe>
</body>
</html>
As you can see, once the first Iframe is loaded, I get the second one and clone it. I then reinsert it in the dom, so I can get access to the onload event. Once this one is loaded, I retrieve the content from non-cloned one (must have loaded as well, since they use the same src). You can then do wathever you want with the content.
Here is the Test_Iframe.html file :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>Test_Iframe</div>
<iframe src="Test_Iframe2.html">
</iframe>
</body>
</html>
and the Test_Iframe2.html file :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>I am the second nested iframe</div>
</body>
</html>
You probably have a timing issue. Your document.ready commend is probably firing before the the second iFrame is loaded. You dont have enough info to help much further- but let us know if that seems like the possible issue.
You should use live method for elements which are rendered later, like colorbox, hidden fields or iframe
$(".inverter-value").live("change",function() {
elem = this
$.ajax({
url: '/main/invertor_attribute/',
type: 'POST',
aysnc: false,
data: {id: $(this).val() },
success: function(data){
// code
},
dataType: 'html'
});
});
I think the best way to reach your div:
var your_element=$('iframe#uploads').children('iframe').children('div#element');
It should work well.
If browser supports iframe, then DOM inside iframe come from src attribute of respective tag. Contents that are inside iframe tag are used as a fall back mechanism where browser does not supports iframe tag.
Ref: http://www.w3schools.com/tags/tag_iframe.asp
I guess your problem is that jQuery is not loaded in your iframes.
The safest approach is to rely on pure DOM-based methods to parse your content.
Or else, start with jQuery, and then once inside your iframes, test once if typeof window.jQuery == 'undefined', if it's true, jQuery is not enabled inside it and fallback on DOM-based method.

Javascript: Can't get element using getElementById [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
Ok. I need fresh eyes because I'm still on this s***d problem for one hour!
Here is my simple HTML code (testssio.html) that include javascript script:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.html = "it finally works!";
</script>
</head>
<body>
<div id="ssio"></div>
</body>
</html>
But it doesn't work! Using the debugger, I get:
Uncaught TypeError: Cannot set property 'html' of null /testssio/:6
Does anyone get it? I know it's not the correct place to look for debugging help, but I'll be crazy if I don't get it! So please, any help?
Tahnks in advance.
The reason for this is that scripts in the head load before the page is rendered. This means your content is not yet rendered and therefore not a part of document.
If you want to see this work, try moving your script below the element renders, like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="ssio"></div>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.innerHTML = "it finally works!";
</script>
</body>
</html>
A more standardized way of doing this is with events. Many people use jQuery but it can be done with plain js. This would mean changing your script like this:
<script type="text/javascript">
function WinLoad() {
var ssio = document.getElementById('ssio');
ssio.innerHTML = "It finally works!";
}
window.onload = WinLoad;
</script>
This way you can still leave it in the <head>.
Also, using .html is from jQuery. It is generally used as .html(content). If you want to use the plain javascript version use .innerHTML = content.
I mention jQuery so much because it is a highly used API. This quote is from their site:
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.
Your code is running too early before the DOM is loaded and thus document.getElementById() doesn't find the element in the document yet.
You can either move your script tag down to right before the </body> tag or you can wait for the DOM to load before running your code with either the window onload event or a DOMReady event.
There are two errors here. First, you need to put the SCRIPT tag after the element. Second, it's not .html, but .innerHTML. So here is the corrected code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="ssio"></div>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.innerHTML = "it finally works!";
</script>
</body>
</html>
you can use something like this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
document.onload= function(){
var ssio = document.getElementById('ssio');
ssio.html = "it finally works!";
}
</script>
</head>
<body>
<div id="ssio"></div>

Manipulating DOM with (framework-less) javascript

Ok, I haven't been using JavaScript without JQuery for quite some time now... But, as coding goes, I have to do without it's power for a project where I can't be sure that JQuery is provided.
The thing I'm trying to do would be the following using JQuery:
$(document).ready(function() {
$('#myDiv').append('<ul><li>a</li><li>b</li></ul>');
});
Now to the non-jquery thing, this is what I have and I really can't understand why it isn't working:
<html>
<head>
<script type="text/javascript">
function load() {
var s = '<ul><li>a</li><li>b</li></ul>';
var element = document.getElementById("myDiv");
element.innerHtml += s;
}
</script>
</head>
<body onload="load()">
<div id="myDiv"></div>
</body>
</html>
Thing is, nothing happens (the function gets called though). Could it be that the DOM isn't ready when load() is called?. I vaguely remember this code working in the firefox 2.x IE7 era ...
What would be the (a) right solution?
It's innerHTML not innerHtml. Notice the upper case HTML. Change that and it should work fine! Here's a working example.
By using innerHtml you are simply creating a new property on the element object and giving it the value of s.
<html>
<head>
<script type="text/javascript">
function load() {
var s = '<ul><li>a</li><li>b</li></ul>';
var element = document.getElementById("myDiv");
element.innerHTML += s;
}
</script>
</head>
<body onload="load()">
<div id="myDiv"></div>
</body>
</html>
JS is case sensitive
I think you want element.innerHTML += s;.

Categories

Resources