Why can the class be picked up by Javascript while loading the page and the ID not?

Asked

Viewed 131 times

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.

1 answer

9


The reason for this is simple. Other than a getElementById, that returns a HTMLElement or null, getElementsByClassName returns a HTMLCollection, which is an iterable object, similar to the standard array, but with the difference that Htmlcollection is updated by the browser when a mutation occurs in the DOM.

When you use getElementsByClassName before the DOM is loaded, you will receive an empty list, but as the new elements are loaded into the DOM, this list is filled in for you. If at any time any element is deleted or added to the DOM, this list will be updated, as you can see in the example:

const paragrafos = document.getElementsByClassName('paragrafo');
const paragrafo2 = document.getElementById('paragrafo2');

paragrafo2.remove();
console.log(paragrafos); 
//A referência de paragrafo2 não existe mais no HTMLCollection "paragrafos"
<p id="paragrafo1" class="paragrafo">Paragrafo 1</p>
<p id="paragrafo2" class="paragrafo">Paragrafo 2</p>

Browser other questions tagged

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