0

Given the following HTML file,

<html>
  <head>
     <script>
        function initialize() {
           document.getElementById('id2')
        }
      </script>
  </head>
  <body>
    <div id="id1">
       <div id="id2"></div>
     </div>
  </body>
</html>

I would like to access the inner div tag using the

document.getElementById

function in the html header, which, although I read the contrary, does not seem to work (in Safari 6.0.5.), while it works to access the outer tag.

user695652
  • 3,725
  • 3
  • 32
  • 52
  • 3
    Please show where you place the JavaScript in your HTML file and post your exact JavaScript code. – Felix Kling Jul 18 '13 at 09:10
  • @Felix Kling The script is placed in the html header – user695652 Jul 18 '13 at 09:49
  • possible duplicate of [Why does jQuery or a DOM method such as \`getElementById\` not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Felix Kling Jul 18 '13 at 09:50

1 Answers1

0

Here you have a fiddle that shows that it works. The script needs to be called after the element is created.

<body>
    <div id="id1">
        <div id="id2"></div>
    </div>
    <script>alert(document.getElementById('id2'));</script>
</body>

Or:

<body>
    <script>
        function getElement (id) {
            return document.getElementById(id);
        };
    </script>
    <div id="id1">
        <div id="id2"></div>
    </div>
    <script>alert(getElement('id2'));</script>

</body>
Kaizo
  • 4,025
  • 2
  • 18
  • 26