Cannot Change InnerHTML of span class? - javascript

I'm new to JavaScript and I cannot understand why my html isn't changing?
I have an Iframe and I'm trying to change the .innerHTML of the span class that the Iframe has created in the DOM.
In the DOM structure, the class is called <span class="weather-location">China</span>
I'm just trying to access this by changing it's innerHTML to Taiwan instead.
here is my code:
<html>
<head>
<title>test</title>
</head>
<body onload="myFunction()">
<iframe class="weather" width="100%" height="600px" frameBorder="0"
src="(this is my iframe src code)></iframe>
<script type="text/javascript">
function myFunction() {
document.getElementsByClassName("weather-location")[0].innerHTML = "Taiwan";
}
</script>
</body>
</html>
When I test it in the console log, it brings up that weather-location as [] but whats also bizarre is when I use the selector tool to hover on that weather-location class and go back and re-type in the code it in the console, it changes the class how I wanted?
Also, I don't know if this helps but when it shows up as [] in chrome a little i box pops up saying "value below was evaluated just now".

You can't change the innerHTML of iframes if it's on another domain.
https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe
This kind of iframe is like a window into another webpage you have no control over.
If it is on the same domain you can use something like
var ifr = document.getElementById( yourIframeId );
var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
var theForm = ifrDoc.getElementById( yourFormId );
SO Question: accessing a form that is in an iframe
Credit to : #le_m

Related

how to get element inner <iframe> of <iframe>?

i have simple webpage and in this webpage , tage and thats id "a1" , this contain inner one more tag, and thats id "a2". i want to get element tag that's id="a2" by using javascript .
please helpe me, how can i get <h1> tag using javascript :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>get element from inner iframe </title>
</head>
<body>
<h1>hello world</h1>
<iframe id="a1" >
<iframe id="a2">
<h1 id="b1">help me</h1>
<p id="b2" >for get HTML tag using javascript DOM</p>
</iframe>
</iframe>
</body>
</html>
First of all, you can't put HTML code directly inside an iframe.
You have to separate it into a different file, and then link it by adding a "src" attribute to the iframe.
Now, assuming you have 3 file:
index.html - that contains the reference first iframe (#a1) and points to iframe1.html
iframe1.html - that contains the reference to the second iframe (#a2) and points to iframe2.html
iframe2.html - that contains the desired h1 tag (#b1)
Here is the code you need to get to it:
var iframe1 = document.getElementById('a1');
var iframeDoc1 = iframe1.contentDocument || iframe1.contentWindow.document;
var iframe2 = iframeDoc1.getElementById('a2');
var iframeDoc2 = iframe2.contentDocument || iframe2.contentWindow.document;
var innerH1 = iframeDoc2.getElementById('b1');
Basically, you get each iframe, then you get its inner document, and then you look inside it.
An inline frame is used to embed another document within the current HTML document. Its better to user any other tag in place of iframe. As in your code h1 tag has and id attribute. You can get h1 tag by its id attribute.
var x= document.getElementById("b1");
alert(x.innerHTML);
use
var iframe = document.getElementById('iframeId');// your frame id here
var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
Or you can use
window.frames['frameID'].document.getElementById('frameID')

Click on element within an iframe with no src attribute

I've been struggling with this one for a few hours now.
I am trying to attach click listeners to elements within an iframe with no src attribute. The entire page is basically inside that bad boy.
When I use "inspect element", the body of iframe looks empty (dunno if that has to do with the fact it has no src attribute.
<iframe id="CoverIframe" name="CoverIframe">
#document
<html>
<head></head>
<body></body>
</html>
</iframe>
When I enter the ID of the iframe in the console, it simply returns null, which prevents me from checking the elements it contains via contents().find() or anything else for that matter. I can only see its content (and by extension the elements on the page) by showing the source code (right click>see source).
Any thoughts on this? Is it because of the absence of src attribute? Any way I can get around it?
Thanks,
Alexis
As you noticed, you can't just set the innerDocument of an iframe like that.
However, you can use its (html-5 only)srcDoc attribute to set it,
<iframe id="CoverIframe" name="CoverIframe" srcdoc="
<html>
<head></head>
<body>hello</body>
</html>"
></iframe>
or use a data:text/html;charset=utf-8,<html><head></head><body>hello</body></html>".
<iframe id="CoverIframe" name="CoverIframe" src="data:text/html;charset=utf-8,<html>
<head></head>
<body>hello</body>
</html>"
></iframe>
But for the later, you will soon need to encodeURI() your page.
So the best is probably using javascript :
<script>
var yourHTML = "<html><head></head><body>hello</body></html>";
function loadFrame(e){e.contentDocument.write(yourHTML)};
</script>
<iframe id="CoverIframe" name="CoverIframe" onload="loadFrame(this)">
► Show code fiddle

How to add a javascript function inside the body of iframe

i have a html file with iframe and button in it, Is there a way to add a javascript function inside the body of iframe after I click the button?. Here is my code. Thanks
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
function callMe() {
var frame = $('iframe'),
contents = frame.contents(),
body = contents.find('body');
var script2 = document.createElement("script");
script2.type = "text/javascript";
script2.text = " function setEmployeeId(){var employeeId = 0;};"
$(body).append(script2);
};
</script>
<title>sample</title>
</head>
<body>
<iframe src="page2.html">
</iframe>
<button onClick="callMe();">click</button>
</body>
</html>
The result I want is to be like this.
<html>
<head>
<title>sample</title>
</head>
<body>
<iframe>
<html>
<head>
<title></title>
</head>
<body>
<script>
function setemployeeId() {
var employeeId = 0;
};
</script>
</body>
</html>
</iframe>
</body>
</html>
Hopefully you can clarify a few things for me as we go, but I think I have some bad news for you.
Any content that is loaded in an iframe cannot truly edited unless you own the page that is being loaded, in that case you can just bake in whatever you need into the loaded page.
HOWEVER!
You can still access elements in the iframe by using the contentWindow attribute. That is all laid out for you here: How to pick element inside iframe using document.getElementById
Once you've got the element you want to work with, you can create a function in the parent window and then add a call to the parent window's function using window.parent. That's outlined here: Calling a parent window function from an iframe
So if you wanted to make a button in an iframe alter the contents of the iframe you could use
var elem = document.getElementById('myframe1').contentWindow.document.getElementById('myButton')
and then create a function in your parent window
function changeIt(){
document.getElementById('thingToChangeInIframe_ItsIDintheIframe').property = 'value';
}
and append it to the button with the code
elem.setAttribute('onclick', 'changeIt();');
If you have any clarifications to what you need just comment and we'll work those out. I'm sorry this doesn't use much jQuery but that's not really my forte, but I think the pure javascript is relatively self explanatory.
EDIT: I should clarify that if the iframe is on another domain then your options are pretty much all eliminated. For security reasons you can't mess with the settings on other people's pages when you load them in an iframe.

Access a variable of iframe from parent

script of iframe
<script type="text/javascript" >
var a=5;
</script>
script of parent window
<script type="text/javascript" >
function close()
{
var check=document.getElementById("iframeid").contentDocument.a;
alert(check)
}
</script>
I want to access the variable which is defined inside the iframe from parent. But the above code doesn't work properly can anyone give an idea to implement this.
Using contentWindow instead of contentDocument works for me:
var check = document.getElementById("iframeid").contentWindow.a;
Also, ensure that the domains match and that you are using a webserver to test (I got a protocol warning when testing from the file system).
UPDATE: You're almost definitely better to use the postMessage API.
One method that has always worked reliably for me is for the iFrame to give its parent a reference to its own window when it first loads. The parent can then access all the variables through that reference. This does require that the parent is loaded before the iFrame, but for me that is usually the case.
So in the parent
var iFrameWin;
Then in the iFrame at some point after it has loaded and settled down
parent.iFrameWin = window; //parent now has a ref to the iframe's window
Then, in the parent when it wants a global var contents from the iFrame
alert(iFrameWin.ivar); // shows value if the global 'ivar' in the iFrame
script of iframe:
var a = 5;
window.parent.postMessage(['varA', a], '*'); // put this in some sort of function, ready, or whatever - you can call it multiple times if you need to as the code in the parent is an eventListener
script of parent window:
var b;
// you might want to write these into if statements to make sure that e.data[0] is varA if you have multiple messages coming across
if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', function(e) {
b = e.data[1];
}, false);
} else if (typeof window.attachEvent != 'undefined') { // this part is for IE8
window.attachEvent('onmessage', function(e) {
b = e.data; // you'll probably have to play around with this part as I can't remember exactly how it comes across in IE8 -- i think it will involve slice() iirc
});
}
Most of my knowledge on this topic comes from Ben Vinegar's talk on Seamless iFrames
This is a cross-domain "okay" method to deal wit this stuff. I'm sure there are some security holes, just as with anything on the web.
See if this works for you:
i created this parent.html page and put an iframe in it with a text input which will show the value passed from iframe window:
<html>
<head>
<title>IFrame Example</title>
<script language="javascript">
function hello(string){
var name=string
document.getElementById('myAnchor').value=name;
}
</script>
</head>
<body>
<iframe namne="iframe" id="iframe_id" src="inputForm.html" height="150" >
</iframe>
Name: <input type="text" id="myAnchor" >
</body>
</html>
and this iframe content page:
<html>
<head>
<title>IFrame Child Example</title>
</head>
<body>
<form name="frm2" >
<h1><font color="#000099">Input Form</font></h1>
<p>Name : </p><input type="text" name="resp" id="input" value=""/>
<input type="button" onclick="parent.hello(this.form.resp.value);" value="Submit" />
</form>
</body>
</html>
clicking the button i get the value in my parent window.
Play with it if you get something with this one.
document.getElementById('ID_OF_IFRAME').document.getElementById('f1')
Note that cross-domain restrictions will still apply.
This is how SharePoint do it when passing argument values from the parent window to the iframe. It's simple, but it works.
<html>
<body>
<iframe id="iframe1"></iframe>
<script type="text/javascript">
var ifr = window.document.getElementById("iframe1");
ifr.dialogArgs = "Hello from the other side.";
ifr.src = "iframeContent.html"
</script>
</body>
</html>
Inside iframeContent.html:
<html>
<body>
<input type="button" value="Click Me!" onclick="alert(window.frameElement.dialogArgs);" />
</body>
</html>
The other way around (accessing ifr.dialogArgs from the parent window after having its value modified by the iframe document) also works.

Display iframe div contents on parent page

I'm sure this is pretty basic, but I can't seem to get any of the solutions I've found to work for me. Basically, I need to get the contents of a div from an iframe, and write them to a div in the parent page. This is what I have:
<iframe src="slideshows/slideshow/case2.html" frameborder=0 scrolling="no"
id="frame1" name="frame1"></iframe>
<div id="caption">
<script type="text/javascript">
var caption = frame1.document.getElementById('slidecaption');
document.write(caption);
</script>
</div>
'slidecaption' is the name of Id in the iframe that I'm trying to grab.
All I get is "null". Is it because the iframe contents haven't loaded yet? If so, how do I delay until the iframe has loaded?
Thanks,
Scott
Thanks to both of you for your help. I figured it out, based on Márcio's idea:
I put the function in the parent page:
<script type="text/javascript">
function send() {
document.getElementById('slidecaption').innerHTML =
frame1.document.getElementById('slidecaption').innerHTML}
</script>
And I put the call in the iframe document:
<body onload="parent.send();">
Regards,
Scott
I'm not sure this is the only thing you need to do, but you certainly need to retrieve frame1 from the dom.
<script type="text/javascript">
var frame1 = document.getElementById('frame1');
var caption = frame1.contentWindow.document.getElementById('slidecaption');
document.write(caption);
</script>

Categories