0
I have an HTML with a linked Javascript file. In Javascript I try to access an element of this HTML through Document.getElementById("meuId") and is returning Null.
That should happen?
In Javascript:
const formCadNot = document.getElementById("cadastrar-noticia")
In HTML:
<script src="js/cadastrarNoticia.js"></script>
...
<form class="formulario" id="cadastrar-noticia" action="cadastraNoticia">
...
Note: the script path in "src" is correct. Inside the folder where my HTML is has a folder "js" with the file registering Oticia.js
depends, where did you try to do this? had already uploaded the html document? tried to put the script at the end of the html file?
– Ricardo Pontual
I loaded the script already in the head of html. If I put the script straight into the html it works. But I want it in a separate file. It will get a lot of script in index.html
– Lucas Pletsch
@Lucaspletsch Use the event
window.onload
to execute the code after page loading.– Valdeir Psr
this happens because the document has not yet been loaded and already tried to access an element that was not yet from
document
. Place your code inside a block that runs when the entire document is loaded, for example:document.addEventListener("DOMContentLoaded", function(){ seu código aqui });
– Ricardo Pontual
read more here: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

– Ricardo Pontual
The value of
formCadNot
will beNULL
... because the script was fired before the element was rendered, only changing the behavior when using the attributedefer=""
on the tagSCRIPT
. One can use thewindow.onload
, orDOMContentLoaded
(this is similar to Defer because it does not expect images and other external resources, just the document), Inkei at the top of your question everything you need to know about this.– Guilherme Nascimento
@Ricardopunctual your tip better solved my problem. If you want to post as solution, I mark it as solved from there.
– Lucas Pletsch