As already said in answer from Ricardo, getElementsByTagName
and getElementsByClassName
return an array of elements. But if you want, there is the alternative to use querySelector
and querySelectorAll
.
In the specific case of tag body
, there can only be one of them in the HTML document, so there’s no point in using it getElementsByTagName
, you can simply use document.querySelector('body')
, in which it will already be possible to call addEventListener
. Although in the case of body
, you can get it directly with document.body
, that the result is the same:
console.log(document.body === document.querySelector('body')); // true
As an alternative to getElementsByClassName
, you can use document.querySelectorAll('.primeiro')
to search for all elements that have the class primeiro
(and note that there is a point before "first", to indicate that it is a class - other than getElementsByClassName
, that does not need the point).
Then the passage referring to body
would look like this:
document.body.addEventListener('scroll', change);
But in fact, the scroll
in the body
does not work as you expect (see here). So that a scroll on the screen fire the event, add it directly into the document
:
document.addEventListener('scroll', change);
function change() {
document.querySelectorAll('.primeiro')
// para cada elemento encontrado, adicione a classe "destaque"
.forEach(e => e.classList.add('destaque'));
}
body {
height: 200px;
}
.destaque {
color: red;
}
<body>
<p class="primeiro">Primeiro</p>
<p>Segundo</p>
<p class="primeiro">Outro Primeiro</p>
</body>