Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get all iframe elements?

I'm showing a loading indicator while some external iframes are loaded with the following code:

<html>

    <head>
        <title>Loading iframe</title>
    </head>

    <script>


    function loading_iframe(){
        document.getElementById('loading_iframe').style.display = "none";
        document.getElementById('loading').style.display = "";
        document.getElementById('loading_iframe').onload = function(){
            document.getElementById('loading').style.display = "none";
            document.getElementById('loading_iframe').style.display = "";
        }
    }
    </script>

    <body>
        <iframe id="loading_iframe" src="iframe.html" width="800" height="100"></iframe>
        <div id="loading">Loading...</div>


        <script>
            loading_iframe();
        </script>
    </body>
</html>

Problem is I'm running around 50 mini iframes per page and I don't fancy rewriting the code above to match each iframe id.

Is there a way I could match each iframe id with a regex, for example:

  • loading_iframe1
  • loading_iframe2
  • loading_iframe3
like image 639
Webby Avatar asked Sep 22 '10 22:09

Webby


1 Answers

First, <script> tags should go either in the <head> or the <body> but not in between!


I would change your naming scheme slightly to this:

<iframe id="iframe1" src="iframe.html" width="800" height="100"></iframe>
<div id="iframe1-L">Loading...</div>

<iframe id="iframe2" src="blah.html" width="800" height="100"></iframe>
<div id="iframe2-L">Loading...</div>

Now you just have to loop through all the iframes, and you can easily access the corresponding div by changing the ID to +"-L"

To get all the iframe elements use getElementsByTagName(), then iterate over those with a for loop:

Something like this:

var i, frames;
frames = document.getElementsByTagName("iframe");
for (i = 0; i < frames.length; ++i)
{
      // The iFrame
    frames[i].style.display = "none";
      // The corresponding DIV
    getElementById(frames[i].id + "-L").style.display = "";
    frames[i].onload = function()
    {
        getElementById(frames[i].id + "-L").style.display = "none";
        frames[i].style.display = "";
    }
}
like image 187
Peter Ajtai Avatar answered Oct 22 '22 10:10

Peter Ajtai