0

my question is quite easy. code as belows:

<div id="parent">
  <script>
    // will this line be an error ? cannot find the dom?
    var dom = document.getElementById("parent");
  </script>
</div>

I test it in all broswers I can find, even IE6, it works well! But I wonder if any browser will make an error? Because after putting the code onto the network, some data tell me that it may result in an error? but how ? could you help me?


@2017.09.13 it seems to be a misunderstand, the code is ok

hanzichi
  • 609
  • 2
  • 12
  • 22

1 Answers1

1

Your script should always be able to find its container element, because the element is included on the page before the script runs. but:

  • Modifying the DOM before it is completely loaded may result in problems in older browsers: https://stackoverflow.com/a/403992/5742681

  • There may be problems accessing any child elements that are included in the parent after the script through the variable defined in the div.

Overall, it would probably be better to put your script outside the div.

Community
  • 1
  • 1
KWeiss
  • 2,954
  • 3
  • 21
  • 37