How to mark a link when pressing, without marking another one with javascript?

Asked

Viewed 34 times

-1

Guys, I have the following navigation bar. However I would like to click on a link, add the bordered class to it. Until then quiet, but when I press on another he also wins the class. Someone can help me ?

const links = document.querySelectorAll('ul li a');
for (let i = 0; i < links.length; i++) {
  links[i].onclick = function() {
    this.classList.add('bordered');
  }
}
ul li {
  margin: 10px 0;
}
ul li a.bordered {
  border-bottom: 3px solid #000;
}
ul li a {
	color: black;
  text-decoration: none;
}
<ul>
  <li><a class="home" href="#">HOME</a></li>
  <li><a href="#">AMBIENTES</a></li>
  <li><a href="#">POSSIBILIDADES</a></li>
  <li><a href="#">SOBRE MIN <i class="fas fa-sort-down"></i></a>
    <ul>
      <li><a href="#">MINHA HISTÓRIA</a></li>
      <li><a href="#">PODER DE MATERIALIZAÇÃO</a></li>
      <li><a href="#">REVISTA DIGITAL</a></li>
    </ul>
  </li>
  <li><a href="#">BLOG</a></li>
  <li><a href="#">LOJAS</a></li>
  <li><a href="#">CONTATO</a></li>
</ul>

1 answer

2

You need to remove the element class by adding earlier, see the changes in the code below:

const links = document.querySelectorAll('ul li a');
for (let i = 0; i < links.length; i++) {
  links[i].onclick = function() {
    // selecione o elemento que tem a classe bordered
    const bordered = document.querySelector('ul li a.bordered');
    if (bordered) {
        // se o elemento existir remove a classe
        bordered.classList.remove('bordered');
    }
    this.classList.add('bordered');
  }
}

Jsfiddle:
https://jsfiddle.net/charlesartbr/r2g8wx9j/

  • 1

    Many thanks friend ! Everything in double !!

Browser other questions tagged

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