Get the element inside the iframe and assign it a value using java script

I am using the User / Html Editor, which has an iframe, since I cannot directly change its value from javascript, I just want to add text to the body iframe tag.

The problem is that I can get the iframe element, but how can I get it? also how can i write text to it?

Example: Iframe looks something like this:

<iframe>
<html>
<body>
----Here I want to write a text-----
</body>
</html>
</iframe>
+3
source share
3 answers

Using only vanilla JS:

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 fix any cross-browser issues) ( unchecked ):

$('#myIFrameId body').append('<div>some new content here</div>');

- , , iframe , .

+3

:

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

Say you have an iframe that looks like this:

<iframe id="theID"> ... </iframe>

and inside the iframe you have an element that 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');
0
source

Source: https://habr.com/ru/post/1793893/


All Articles