2

I have inherited some javascript code which directly accesses an iframe by its name, without any getElementById() or anything. I can't find any sign that this is actually legal, yet it seems to work in the browsers I've tried it in (Chrome, Firefox, IE10, Safari for Windows).

Simple test case:

<iframe name="iFrameName" id="iFrameId" src="test2.html"></iframe>
<button onclick="iFrameName.myFunction();">click me</button>

And the test2.html src of the iframe contains:

<script type="text/javascript">
    function myFunction()
    {
        alert("OH HAI!");
    }
</script>

Clicking on the button works perfectly - the alert "OH HAI" pops up.

How does this work? Should it work? Is it safe to rely on or should I be using getElementById() to retrieve the iframe?

DCatDC
  • 23
  • 2

1 Answers1

2

How does this work? Should it work?

Yes, there was a time when elements could only be accessed by name, and most (all?) browsers still support it. See the QuirksMode page about it, it was written years ago but still applies.

Is it safe to rely on or should I be using getElementById() to retrieve the iframe?

You should be using document.getElementById() and other modern methods. If you rely on names, your code will soon become a mess.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150