Hi_TecH
Hi_TecH

Reputation: 427

How to change a function from forEach() to a function for working with one element JS

I am new to pure JS. I have a code like this, which when clicking on an element keeps the scroll position after reloading the page:

let cords = ['scrollX','scrollY'];
document.querySelectorAll('.scroll').forEach(el => {
    el.addEventListener('click', () => {
        cords.forEach(cord => localStorage[cord] = window[cord]);
    });
});
window.addEventListener('load', e => {
    if (localStorage[cords[0]]) {
        window.scroll(...cords.map(cord => localStorage[cord]));
        cords.forEach(cord => localStorage.removeItem(cord));
  }
});

But this is for the case when we have many elements with such a class. How can we change this function to work if we have only one instance of this class?

Thanks!

Upvotes: 0

Views: 79

Answers (1)

jWhiteside
jWhiteside

Reputation: 127

The Document.querySelectorAll() method returns an array of matching elements. Array.forEach() iterates through each item and performs an action, in this case a function which adds an event listener. This method should still work for an array with only one item.

Upvotes: 1

Related Questions