I recently came across some JavaScript code that directly accesses an iframe
by its name, without using getElementById()
or any other method. Surprisingly, this code seems to be functioning properly in browsers like Chrome, Firefox, IE10, and Safari for Windows, even though I couldn't find any official documentation stating that this approach is legal.
For example, consider the following simple test case:
<iframe name="iFrameName" id="iFrameId" src="test2.html"></iframe>
<button onclick="iFrameName.myFunction();">click me</button>
The content of the test2.html src file within the iframe includes the following script:
<script type="text/javascript">
function myFunction()
{
alert("OH HAI!");
}
</script>
Surprisingly, clicking on the button triggers the expected behavior, displaying an alert message saying "OH HAI!"
Now, the question arises - how is this code functioning without using getElementById()
? Is it reliable and safe to use this method, or should I stick to conventional practices and use getElementById()
to access the iframe?