How to dynamically remove and add HTML class with Javascript

Asked

Viewed 104 times

0

I managed to solve through Jquery, but wanted a solution only in pure Javascript.

I have a nav with 4 links on header, to li where the usurer is in a class selected by default, which changes the color and creates a small trace underneath.

My goal is: to happen one hover in any of the li's, this class selected skirt of li main and go wherever the mouse is.

var navegacaoA = document.querySelector('nav a');
navegacaoA.addEventListener("mouseover", function() {
    let navegacaoLi = document.querySelector('nav li');
    if (navegacaoLi.classList.contains('selected')) {
        navegacaoLi.classList.remove('selected');
        this.classList.add('selected');
    }
})
<nav>
  <ul>
    <li class="selected"><span></span><a href="">Invisalign</a></li>
    <li><a href="">Benefícios</a></li>
    <li><a href="">Serve para mim?</a></li>
    <li><a href="">Contato</a></li>
  </ul>
</nav>

  • What is the purpose of this class? Stylization? So why not do it directly by :hover of the CSS?

2 answers

1

You’re complicating too much, you don’t need any JS to underline/underline mouseover, just CSS:

a {
  text-decoration: none;
  }
  
a:hover {
  text-decoration: underline;
  }
<nav>
  <ul>
    <li><a href="">Invisalign</a></li>
    <li><a href="">Benefícios</a></li>
    <li><a href="">Serve para mim?</a></li>
    <li><a href="">Contato</a></li>
  </ul>
</nav>

0


Hello, I don’t know if this is the best solution, but from what I understand about your need, it works. Instead of using class, I used an attribute, which we can easily style and disable via javascript

    var li = document.querySelectorAll('li')
    var liSelected = document.querySelector('[selected=true]')
    for(var i = 0; i < li.length; i++){
        li[i].addEventListener('mouseover', function(){
            liSelected.setAttribute('selected', false)
            this.setAttribute('selected', 'true')
        })
        li[i].addEventListener('mouseleave', function(){
            liSelected.setAttribute('selected', true)
            this.setAttribute('selected', 'false')
        })
    }
a {
  color: #000;
  text-decoration: none;
}

[selected=true] a{
  text-decoration: underline;
  color: #00b;
}
<nav>
  <ul>
    <li selected="true"><a href="">Invisalign</a></li>
    <li selected="false"><a href="">Benefícios</a></li>
    <li selected="false"><a href="">Serve para mim?</a></li>
    <li selected="false"><a href="">Contato</a></li>
  </ul>
</nav>

Browser other questions tagged

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