"Document" can be accessed in a separate HTML Javascript file?

Asked

Viewed 87 times

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

  • 1

    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?

  • 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

  • 1

    @Lucaspletsch Use the event window.onload to execute the code after page loading.

  • 1

    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 });

  • 1

    read more here: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded&#Xa

  • The value of formCadNot will be NULL ... because the script was fired before the element was rendered, only changing the behavior when using the attribute defer="" on the tag SCRIPT. One can use the window.onload, or DOMContentLoaded (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.

  • @Ricardopunctual your tip better solved my problem. If you want to post as solution, I mark it as solved from there.

Show 2 more comments

1 answer

1


The problem is that you are loading your script before loading the element with your id. So in the script you try to get an element that does not exist.

The solution to this problem is to import the script below the element or create a function to be called by the event onload when the page is loaded.

See the example below:

function setColor() {
    const div = document.getElementById("myDiv");
    div.style.color = "#f00";
    div.innerText = "Texto colorido com o Javascript.";
}
<body onload="setColor();">
    <div id="myDiv">
        Texto não colorido.
    </div>
</body>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.