.addeventlistener is not a Function

Asked

Viewed 881 times

3

I want to add an event when the page scrolls, but the following error occurs:

Uncaught TypeError: document.getElementsByTagName(...).addEventListener is not a function

Follows code:

document.getElementsByTagName('body').addEventListener('scroll', change)

function change() {
    document.getElementsByClassName('primeiro').classList.add('destaque')
 }

How can I correct?

2 answers

4

getElementsByTagName returns an array of objects, to use the addEventListener it needs to be a single object, so this error happens.

Since it is an array, you can take the first element and select the event, for example:

document.getElementsByTagName('body')[0].addEventListener('scroll', change);

Or it could associate to each element (the body will only have one in the document, but if it were another element as a div, this works well) and Tack the event:

var elementos = document.getElementsByTagName('body');
for(i=0;i<elementos.length;i++) {
    elementos[i]..addEventListener('scroll', change);
}

2


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>

Browser other questions tagged

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