1

I am working on the below nav bar

<nav class="nav" >
        <ul class="nav__list">
            <li id="authors-tag" class="nav__list__item"><a class="nav__list__item__link" href="#">Authors</a></li>
            <li id="publishers-tag" class="nav__list__item"><a class="nav__list__item__link" href="#">Publishers</a></li>
            <li id="books-tag" class="nav__list__item"><a class="nav__list__item__link" href="#">Books</a></li>
        </ul>
    </nav>

By using pure JS, I am trying to add an event listener to each tab of the nav bar, so that when the user clicks on a li item, the tab will be made active by adding a modifier class to that DOM element to highlight it.

So far every answer I've found is using jQuery.

Below's my main.js

const tabs = document.querySelectorAll('.nav__list__item__link');
tabs.forEach(clickedTab =>{
  clickedTab.addEventListener('click', () => {
    tabs.forEach( tab => {
      tab.classList.remove('active');
    });
    e.target.classList.add('.active');
  });
});

I've also tried using getAttribute by id but I just can't seem to nail it.

Thanks in advance.

alexGH
  • 25
  • 6

1 Answers1

0

Just remove the . from e.target.classList.add('.active');, e.g. e.target.classList.add('active');.

const tabs = document.querySelectorAll('.nav__list__item__link');
tabs.forEach(clickedTab =>{
  clickedTab.addEventListener('click', () => {
    tabs.forEach( tab => {
      tab.classList.remove('active');
    });
    e.target.classList.add('active');
  });
});
Vahid Al
  • 1,581
  • 1
  • 12
  • 24
  • It's nice if you can explain why removing the dot will fix the issue. – Vahid Al Jan 05 '22 at 15:46
  • 3
    It does not need a dot in `classList.add` and `classList.remove`. – Ali Tehrani Jan 05 '22 at 15:48
  • While this is a correct answer, SO discourages typo questions (they cannot be searched, and don't have any value for anyone other than the OP). For that reason, in the future, you shouldn't answer them; leave a comment and flag the question for closure instead. – FZs Jan 05 '22 at 15:50