6
I was doing some tests with Javascript and I came across an interesting "phenomenon", but I could not find a good explanation to explain it.
Follows the code:
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet">
<title>Documento</title>
<script src="script.js"></script>
</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>
</body>
</html>
If you try to capture the paragraph (<p>
) who owns the id="ponto"
using the following Javascript:
let p1 = document.getElementById("ponto")
console.log(p1);
The result will be null
, since Javascript is being loaded before the creation of a paragraph with id="ponto"
, in this case, the script is being loaded into the head
, and the paragraph in body
.
On the other hand, if we try to use:
let para = document.getElementsByClassName("Paragrafo")
console.log(para)
Javascript will return to class
, even though it was executed before it, that is, when Javascript is executed, as well as the ID, the class did not yet exist in the DOM. So how does Javascript manage to return the class?
Note: I know this problem can be solved through specific events like window.onload
or DOMContentLoaded
, but this is not the case now, since the question is why we can get through the class, but not through the ID.