Modifying the iframe source in several tags. the javascript function does not work

advertisements

I'm trying to execute a javascript function that would change the source code for each iframe. It works if the iframe is not within any other tags.

<!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<button onclick="myFunction()">Search</button>
<iframe src="https://www.espn.com"  frameborder="1"  width="500" height="320"></iframe>
<iframe src="https://www.nbc.com"  frameborder="1"  width="500" height="320"></iframe>
<iframe src="https://www.cnn.com"  frameborder="1" width="500" height="320"></iframe>
 <script type = "text/javascript">
  function myFunction(){
  alert("Hello!");
  var frames = window.frames;
  for (var i = 0; i < frames.length; i++){
    frames[i].location = "http://www.w3schools.com";
    }
}
</script>
</body>
</html>

How ever if I put the iframe within div tags the javascript for some reason doesn't reach them.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
 <div class="container-fluid">
    <form align = "center">
      <br>
      <button onclick="myFunction()">Search</button>
      <br>
    </form>
<div class="col-xs-8 col-lg-6">
    <h3 id = "ESPN">ESPN</h3>
       <iframe src="https://www.espn.com"  frameborder="1"  width="500" height="320"></iframe>
      <br>
    </div>
    <div class="col-xs-8 col-lg-6">
    <h3 id = "NBC">NBC</h3>
      <iframe src="https://www.nbc.com"  frameborder="1"  width="500" height="320"></iframe>
      <br>
    </div>
    <div class="col-xs-8 col-lg-6">
    <h3 id = "CNN">CNN</h3>
      <iframe src="https://www.cnn.com"  frameborder="1" width="500" height="320"></iframe>
      <br>
</div>
</div>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
 <script src="js/bootstrap.min.js"></script>
 <script type = "text/javascript">
  function myFunction(){
  alert("Hello!");
  var frames = window.frames;
  for (var i = 0; i < frames.length; i++){
    frames[i].location = "http://www.w3schools.com";
    }
}
</script>
</body>
</html>

Is there something else I need to do in order for my function to read the iframes?


  function myFunction(){
  alert("Hello!");
  var frames = window.getElementsByTagName("iframe"); // You only want iframes
  for (var i = 0; i < frames.length; i++){
    frames[i].src = "http://www.w3schools.com";
    }
}