Access the contents of an iframe via javascript

Asked

Viewed 221 times

0

I have an html document named frame.html with the following code:

<html>
<head>
    <title>frame</title>
</head>
<body>
    <span id="teste">teste</span>
</body>

And another html document with the name index.html:

<html>
<head>
    <title>index</title>
</head>
<body>
    <iframe src="frame.html" id="frameq"></iframe>
</body>
</html>

i intend to access content from within iframe from a script in index.html as an example:

document.getElementById('teste').style.backgroundColor = "#f00";

1 answer

1

Every window has its own document, then the document iframe is another. For your example:

var iframe_document = document.getElementById('frameq').contentWindow.document;

From this Document you can make the style change - but only if the two documents are from the same domain, otherwise there are security restrictions.

iframe_document.getElementById('teste').style.backgroundColor = "#f00";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.