Hello,
As some friends have already said here, you are trying to catch an element that does not yet exist DOM, because what is inside the tag body
shall be executed only after the execution of the elements of head
.
There are some simple solutions to your problem. The first (but not widely used) is to tag script after body. See:
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet">
<title>Documento</title>
</head>
<body>
<h1>Titulo</h1>
<p class="Paragrafo" id="ponto">Paragrafo 1</p>
<p class="Paragrafo" >Paragrafo 2</p>
<p id="p3">Paragrafo 3</p>
<script src="script.js"></script>
</body>
</html>
Another solution is to make your javascript code wait for the creation of window
in the DOM, using the window.onload
. This solution is more archaic than the following. See:
window.onload = function(){
let p1 = document.getElementById("ponto")
console.log(p1);
};
The most "up-to-date" solution is using the DOMContentLoaded
, an event triggered when all HTML is created and analyzed, without waiting for Images, CSS and others to load. See:
document.addEventListener("DOMContentLoaded", function(event){
let p1 = document.getElementById("ponto")
console.log(p1);
});
I hope I helped, hug!
If you arrow the id would not even need to do this function... just call
ponto
– SylvioT
You are trying to select an element that does not yet exist in the DOM, because you loaded the JS at the beginning of the file, before the elements; for this reason it is recommended to put the JS files at the end of the HTML.
– Woss
involves the js code in
window.onload = function () { /* codigo aqui */ };
– vik
Possible duplicate of Where should I put a Javascript code in an HTML document?
– Woss