admin管理员组

文章数量:1401610

I wonder why the following doesn't work:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Iframe</title>
    <style>
    </style>
</head>

<body>
    <iframe name="myFrame"></iframe>
    <script>
        window.frames["myFrame"].style.background = "green";
    </script>
</body>

</html>


However, if you access the iframe directly using its ID, it works with no problem:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Iframe</title>
    <style>
    </style>
</head>

<body>
    <iframe id="myFrame"></iframe>
    <script>
        document.getElementById("myFrame").style.background = "green";
    </script>
</body>

</html>


How can I use window.frames to get the first code to run properly?

I wonder why the following doesn't work:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Iframe</title>
    <style>
    </style>
</head>

<body>
    <iframe name="myFrame"></iframe>
    <script>
        window.frames["myFrame"].style.background = "green";
    </script>
</body>

</html>


However, if you access the iframe directly using its ID, it works with no problem:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Iframe</title>
    <style>
    </style>
</head>

<body>
    <iframe id="myFrame"></iframe>
    <script>
        document.getElementById("myFrame").style.background = "green";
    </script>
</body>

</html>


How can I use window.frames to get the first code to run properly?

Share Improve this question asked Feb 9, 2014 at 6:53 MoriMori 6,96219 gold badges70 silver badges104 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

I think you have to do a for loop to find all the frames and then access them by their index.

for(var i=0; i < frames.length; i++) {
    console.log(frames[i]);
}

This doesn't work for you, because it will return the window object inside of the frame and not the iframe element. If you want to use the name attribute you can use document.getElementsByName("myFrame")[0] but I'd remend accessing it by id.

It should work the same for getElementsByName, mind you that it returns an array of element, not an element.

Both statements should have the same effect for frame with name of "myFrame", and id of "myFrame":

document.getElementsByName("myFrame")[0].style.background = "green";
document.getElementById("myFrame").style.background = "green";

本文标签: javascriptGet iframe with windowframes property vs iframe IDStack Overflow