0

I have this function:

    var togView = document.querySelector('.toggle-view');
    var list = document.querySelector('.pt-list');

    togView.onclick = function() {
        const isAdded = togView.classList.toggle('list');
        list.classList.toggle('list', isAdded);
    };

Which I'm using to toggle a class called .list on and off on this little element called toggle-view and on a sibling element called pt-list

<div class="toggle-view">
   <span class="thumb-view">Thumbnail View</span> | <span class="list-view">List View</span>
</div>

<div class="pt-list"></div>

This worked fine until I added another <div class="toggle-view"> element. Now only the first iteration of the toggle-view element works.

How could I get this function to work on both <div class="toggle-view"> elements independently without having to assign them an ID and duplicate the function?

I found a similar question on here from a few years ago and from what I understand, I need to use this?, but I can't figure out how to apply that to what's happening in my function.

Any guidance would be appreciated!

DesignAaron
  • 131
  • 7
  • 1
    The docs for [querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) say that only the first match is returned. Use querySelectorAll for multiple selections. – Charlie Bamford May 17 '21 at 18:16
  • 1
    Does this answer your question? [Why does querySelector only select the first element and how can I fix this?](https://stackoverflow.com/questions/55012836/why-does-queryselector-only-select-the-first-element-and-how-can-i-fix-this) – Charlie Bamford May 17 '21 at 18:17

1 Answers1

0

You can use "document.querySelectorAll('.toggle-view')" and querySelectorAll will return a list of html elements with class name of ".toggle-view". Then use foreach loop through this list and add click listener to trigger click event independently.

See the snippet below, the result might be vary, but logic is there:

var togView = document.querySelectorAll('.toggle-view');
    var list = document.querySelector('.pt-list');

togView.forEach((button) => {
  button.addEventListener('click', () => {
    const isAdded = button.classList.toggle('list');
    list.classList.toggle('list', isAdded);
    //Test for showing the className onto html element, independently
    button.innerHTML  = button.classList.value
  });
});
<div class="toggle-view">
   <span class="thumb-view">Thumbnail View</span> | <span class="list-view">List View</span>
</div>

<div class="toggle-view">
   <span class="thumb-view">Thumbnail View</span> | <span class="list-view">List View</span>
</div>



<div class="pt-list"></div>
StevenXXCCC
  • 268
  • 1
  • 3
  • 10