Can I use document.getElementById() before the DOM is fully loaded?

Viewed 944

I want to know if it is correct to use document.getElementById() before the DOM is fully loaded.

I mean, under the definition of the DOM element.

Example:

<html>
<head>...
<body>
<div id="hello">...
...
<script>
document.getElementById('hello')...
</script>
...

I tried it and it works, but I want to know if it's okay to do so.

I am aware that I can listen to the DOM load event and act depending on it, but I don't want to do that if it's not strictly necessary.

2 Answers

It's perfectly fine to do that. Scripts are often placed at the end of the <body> tag, so you don't have to wait for the DOM load event.

Prefer to do this way:

<html>
<head>...
<body>
<div id="hello"> 
...

<script>
 const myHello  = document.getElementById('hello');

myHello.onclick=evt=>
  {
...
  }

</script></body></html>
Related