Get an Element inside an Iframe and Assign a Value to it using java script
I am using an User Control/Html Editor in which there is an Iframe, since I can't change the value of it from javascript directly, I want to just append a text in the Iframe's body tag.
The Problem is I can get the Iframe element but how can I get it t开发者_如何学Pythonag? also how can I write a text to it?.
For Example: The Iframe looks something like this:
<iframe>
<html>
<body>
----Here I want to write a text-----
</body>
</html>
</iframe>
Using vanilla JS only:
var iframeElt = document.getElementById('myIFrameId'),
iframeDocument = iframeElt.contentDocument ?
iframeElt.contentDocument : iframeElt.contentWindow.document,
iframeNewDiv = iframeDocument.createElement('div');
iframeNewDiv.innerHTML = 'some new content here';
iframeDocument.body.appendChild(iframeNewDiv);
Using jQuery (which will eliminate any cross-browser issues) (untested):
$('#myIFrameId body').append('<div>some new content here</div>');
Because of security restrictions imposed by the same-origin policy, the iframe must be in the same domain as the parent page for either of these to work.
You can do it like this:
var ifrm = document.getElementById('myIframe');
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.appendChild(document.createTextNode('Hello World!'));
ifrm.document.close();
Let's say that you have an iframe which looks like this:
<iframe id="theID"> ... </iframe>
and inside the iframe, you have an element which looks like this:
<div id="insideID"> ... </div>
Using jQuery, you can do something like this:
$('#theID').contents().find('#insideID').html('This is the inner HTML you want to change');
精彩评论