3

I have a project that uses jQuery. And I am trying to convert this script to Javascript. I had the following line on that script.

var a = $("#myImage");

I changed it to

var a = document.getElementById("myImage");

but script is not working because my page hasn't loaded yet when this happens. I have no idea how to fix this. Any help would be greatly appreciated. Thank you.

Berglund
  • 636
  • 2
  • 7
  • 20
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Heretic Monkey May 06 '20 at 16:42

5 Answers5

2
<body onload="var a = document.getElementById("myImage");">
</body>

onload="var a = document.getElementById("myImage");" runs when the content is fully loaded. When the body is completely loaded then var a = document.getElementById("myImage"); will run.

1

You need to execute the script once the page loads.

window.addEventListener("load", function(){
  // .... Add your script here
});
Sivakumar
  • 349
  • 2
  • 10
1

You can include a listener on the document object to wait for the DOM to be loaded.

document.addEventListener('DOMContentLoaded', function(event) {
  var a = document.getElementById("myImage");
})
Claudio Busatto
  • 721
  • 7
  • 17
1

Try using.

window.addEventListener('DOMContentLoaded', function(){

       var a = document.getElementById("myImage");
       //Rest code here

});
Adeel Tahir
  • 203
  • 2
  • 9
1

You could, for instance:

  1. Place corresponding <script> tag before closing </body> tag.
  2. Start doing things when document is loaded using a callback.

Personally, I prefer the 1st option much more since it works more stably according to my experience.

Igor Bykov
  • 2,532
  • 3
  • 11
  • 19