2

Lets say you have a main .html:

<!DOCTYPE html>
<html>
<head>
    <title>Page One</title>
    <script type="text/javascript" src="javaS.js"></script>
    <link rel="stylesheet" type="text/css" href="CSS.css">
</head>
<body id="main">
<h3>Test switching html content inside iframe</h3>
<p>iframe:</p>
<iframe src="" id="iframe1"></iframe>
</body>
</html>

And a secondary .html:

<!DOCTYPE html>
<html>
<head>
    <title>Page two</title>
    <link rel="stylesheet" type="text/css" href="CSS.css">
</head>
<body id="test">
<h3>Test subject</h3>
<p>subjugate text</p>
</body>
</html>

How would you display the local second .html inside the iframe element of the first .html, using only JavaScript?

I have tried using these snippets:

window.onload = function() {window.frames['iframe1'].location.replace("Secondary.html");}

.

var iframe = document.getElementById('iframe1');
iframe.src = "second.html"; 

...But these haven't worked. I'm new at this so the answer might be fairly obvious, but any guidance would be very much appreciated!

4 Answers 4

2

I use this and it works well:

window.onload = function()
{
    document.getElementById('iframe1').src = "Secondary.html";
}
Sign up to request clarification or add additional context in comments.

Comments

1
document.getElementsByTagName("iframe")[0].setAttribute("src", "http://your-url.com");

Comments

1

Your second snippet is perfect. You just have to make sure that it runs when iframe DOM element exists - in window.onload.

Comments

1

I just combined the two exampples you had tried to make one working example, see here: https://jsfiddle.net/4p18mxg9/9/

var iframe = document.getElementById('iframe1');
window.onload = function() {
    iframe.src = "second.html";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.